当前位置:网站首页>Freecodecamp ---- budget & category exercise
Freecodecamp ---- budget & category exercise
2022-04-23 16:58:00 【Lily's autumn】
1 The analysis of the topic is as follows
1.1 category class
Ask for in category class Four or five functions are defined in :
- deposit(amount, description=''), The following format is added :{"amount": amount, "description": description};
- withdraw() function , And desposit() similar , however amount You need to change it to a negative number , If you have any amount happen , Need to put founds Subtract the corresponding amount value , And back to True, Otherwise return to False;
- get_balance() function , return deposit() Functions and withdraw() The result of the function ;
- transfer(amount, another list) function , Judge funds Is it enough , If sufficient , take deposit() Functions and withdraw() Add the function content , And back to True, vice versa ;
- check_funds() function , When amount > balance of the budget category When to return to False, Otherwise return to True;
- Output function , Title line required 30 Characters , Name centered , On both sides “*” character ,description Align left , Maximum 23 position , Superfluous does not show ,amount Align right , Maximum 7 position , Superfluous does not show , Add a new line Total Show ;
1.2 create_spend_chart() function
For a print function , Requirements are as follows :
- Show each category The percentage spent
- The left side shows 0-100 The label of , use 'o' Characters indicate column height , Not an integer , It should be rounded to the nearest 10 It's about
- The horizontal line should be better than the last one bar Two blank lines
- Every category The name of is in the corresponding bar Vertical display below
- The title at the top is "Percentage spent by category"
2 Sample output
category Output :
*************Food*************
initial deposit 1000.00
groceries -10.15
restaurant and more foo -15.89
Transfer to Clothing -50.00
Total: 923.96
create_spend_chart Output :
Percentage spent by category
100|
90|
80|
70|
60| o
50| o
40| o
30| o
20| o o
10| o o o
0| o o o
----------
F C A
o l u
o o t
d t o
h
i
n
g
3 Source code analysis
This question is very lazy , I didn't write it myself , Translated an article written by a big man .
Original link :FreeCodeCamp----Scientific Computing with Python Projects----Budget-app_m0_43406494 The blog of -CSDN Blog
class Category:
def __init__(self,name):
self.name=name
# Clear title ledger is a list
self.ledger=[]
self.funds=0
# Pre deposit
def deposit(self,amount,description=''):
# The format is required by the title , And description The default value is empty character
self.ledger.append({"amount": amount, "description": description})
self.funds+=amount
# Consumption or withdrawal , And deposit The function is the same ,amount It's a negative number
# Premise is funds Is a positive number , Immediate inventory , return True, Otherwise return to False
def withdraw(self,amount,description=''):
if self.check_funds(amount):
self.ledger.append({"amount": -amount, "description": description})
self.funds-=amount
return True
return False
def get_balance(self):
return self.funds
# other Also a list
def transfer(self,amount,other):
if not self.check_funds(amount):
return False
# Transferred to the other Of list in
# If a transfer occurs ,funds You need to subtract this part of amount, Otherwise, you need to add
# If a transfer occurs ,funds May increase or decrease , Have changed , return True
self.ledger.append({'amount':-amount,'description':"Transfer to {}".format(other.name)})
self.funds-=amount
other.ledger.append({"amount": amount, "description":"Transfer from {}".format(self.name)})
other.funds+=amount
return True
# According to the requirements ,check_funds Use in withdraw() and transfer() in
def check_funds(self,amount):
if self.funds>=amount:
return True
return False
# Printing requirements :
# Title Line 30 Characters , Name centered , On both sides “*” character
# description Align left , Maximum 23 position , Superfluous does not show
# amount Align right , Maximum 7 position , Superfluous does not show
# Add a new line Total Show
def __str__(self):
s=''
s+=self.name.center(30,'*')+'\n'
for x in self.ledger:
if len(x['description'])>23:
s+=x['description'][0:23]
else:
s+=x['description'][0:23].ljust(23)
s+="{0:.2f}".format(x['amount']).rjust(7)
s+='\n'
s+='Total: {}'.format(self.funds)
return s
# It's not round , But to give up a bit !
# categories is a list
# chart Show each category The percentage spent
# The left side shows 0-100 The label of , use 'o' Characters indicate column height , Not an integer , It should be rounded to the nearest 10 It's about
# The horizontal line should be better than the last one bar Two blank lines
# Every category The name of is in the corresponding bar Vertical display below
# The title at the top is "Percentage spent by category"
def create_spend_chart(categories):
s="Percentage spent by category\n"
sum=0
withdraws={}
# The percentage calculation only includes withdrawals
for x in categories:
withdraws[x.name]=0
for y in x.ledger:
if y['amount']<0:
withdraws[x.name]+=y['amount']
withdraws[x.name]=-withdraws[x.name]
for x in withdraws:
sum+=withdraws[x]
for x in withdraws:
withdraws[x]=int(withdraws[x]/sum*100)
for i in range(100,-10,-10):
s+=str(i).rjust(3)+'| '
for x in categories:
if withdraws[x.name]>=i:
s+='o '
else:
s+=' '
s+='\n'
s+=' '*4+'-'*(1+len(categories)*3)+'\n'
maxlen=0
for x in categories:
if len(x.name)>maxlen:
maxlen=len(x.name)
for i in range(maxlen):
s+=' '*5
for x in categories:
if len(x.name)>i:
s+=x.name[i]+' '
else:
s+=' '*3
s+='\n'
return s[0:-1]
if __name__ == "__main__":
food=Category('food')
entertainment=Category('entertainment')
business=Category('Business')
food.deposit(900, "deposit")
entertainment.deposit(900, "deposit")
business.deposit(900, "deposit")
food.withdraw(105.55)
entertainment.withdraw(33.40)
business.withdraw(10.99)
actual = create_spend_chart([business, food, entertainment])
print(actual)
版权声明
本文为[Lily's autumn]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204230555126993.html
边栏推荐
- Get the column name list of the table quickly in Oracle
- TypeError: set_ figure_ params() got an unexpected keyword argument ‘figsize‘
- Feign report 400 processing
- Deeply understand the relevant knowledge of 3D model (modeling, material mapping, UV, normal), and the difference between displacement mapping, bump mapping and normal mapping
- Idea of batch manufacturing test data, with source code
- Path environment variable
- ◰ GL shadow map core steps
- oracle 中快速获取表的列名列表
- Installing labellmg tutorial in Windows
- 正则过滤内网地址和网段
猜你喜欢
随机推荐
websocket
Bytevcharts visual chart library, I have everything you want
STM32__03—初识定时器
Mock test
Use case execution of robot framework
DDT + Excel for interface test
【PIMF】OpenHarmony啃论文俱乐部—在ACM Survey闲逛是什么体验
【解决报错】Error in v-on handler: “TypeError: Cannot read property ‘resetFields’ of undefined”
Selenium IDE and XPath installation of chrome plug-in
ACL 2022 | dialogved: a pre trained implicit variable encoding decoding model for dialogue reply generation
PostgreSQL column storage and row storage
Execution plan calculation for different time types
杂文 谈谈古典的《拆掉思维里的墙》
The new MySQL table has a self increasing ID of 20 bits. The reason is
How vscode compares the similarities and differences between two files
∑GL-透视投影矩阵的推导
Node access to Alipay open platform sandbox to achieve payment function
详解牛客----手套
UWA Pipeline 功能详解|可视化配置自动测试
Nodejs reads the local JSON file through require. Unexpected token / in JSON at position appears