To input a file and get a formatted string output using .format()

2024/11/8 2:46:46

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:

enter image description here

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:

enter image description here

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.

The code so far:

def calculate_expenses(file_name):
file_pointer = open(file_name, 'r')
data = file_pointer.readlines()
list_main=[]
for line in data:name, price = line.strip().split(',')print (name, price)

Output:

('milk', '2.35')
('bread ', ' 1.95')
('chips ', '    2.54')
('milk  ', '    2.38')
('milk', '2.31')
('bread', '    1.90')

I can't get rid of the spaces and don't know what to do next.

Answer

Can be solved by :

def calculate_expenses(filename):file_pointer = open(filename, 'r')# You can use either .read() or .readline() or .readlines()data = file_pointer.readlines()# NOW CONTINUE YOUR CODE FROM HERE!!!my_dictionary = {}for line in data:item, price= line.strip().split(',')my_dictionary[item.strip()] = my_dictionary.get(item.strip(),0) + float(price)dic={}for k,v in my_dictionary.items():dic[k]='${0:.2f}'.format(round(v,2))L=([(k,v) for k, v in dic.iteritems()])L.sort()return L
https://en.xdnf.cn/q/120665.html

Related Q&A

How to use python regex to extract IP address from server log files?

I am currently getting started with python. I have a server log file for the pages I visited over a period of time. How do I write a python program to find out which IP address was visited most? Will …

DateFormatter returning wrong dates - Matplotlib/Pandas [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.Questions concerning problems with code youve written must describe the specific problem — and incl…

What does the error IndentationError: expected an indented block in python mean? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.This question was caused by a typo or a problem that can no longer be reproduced. While similar q…

How to insert character in csv cell in python?

Im new with python. Here is my csv file :data;data;name surname; data; data data;data;name surname; data; data data;data;name surname; data; data data;data;name surname; data; dataThe thing that I want…

How can you initialise an instance in a Kivy screen widget

I am trying to access an instance variable named self.localId in my kivy screen and it keeps saying the saying the instance doesnt exist after i have initialised it. I know I have an error In my code b…

is a mathematical operator classed as an interger in python

in python is a mathematical operator classed as an interger. for example why isnt this code workingimport randomscore = 0 randomnumberforq = (random.randint(1,10)) randomoperator = (random.randint(0,2)…

Fix a function returning duplicates over time?

I have a function here that returns a 4 digit string. The problem is that when I run the function like 500 times or more, it starts to return duplicates. How to avoid that?My Function:import random de…

Pandas method corr() use not all features

I have dataframe with shape (335539, 26). So I have 26 features. But when i use data.corr() I get a 12 x 12 matrix.What can be wrong? `

int to datetime in Python [duplicate]

This question already has answers here:Convert string "Jun 1 2005 1:33PM" into datetime(26 answers)Parsing datetime in Python..?(2 answers)Closed 5 years ago.Im receiving data from the port.…

How to extract the historical tweets from twitter API? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.Want to improve this question? Update the question so it focuses on one problem only by editing this post.Closed 5…