## Maths Coding Question

This is the place for queries that don't fit in any of the other categories.

### Maths Coding Question

Hey,

"If I had £0 at the beginning of 2013, and I gained £50 a week, lost one fifth of all my money every month, and every leap year, one quarter of the money I had lost gets returned. How much money would I have at the end of 10 years?"

This is the question my friend asked me to figure out. I have attempted to write a program, but it only returns "26000.0". Something has gone wrong. Here is my code, and if someone could to kind enough to tell me what the problem is, I would be most grateful.

Code: Select all
total = 0
weeksleft = 520
monthsleft = weeksleft/4
gone = 0
to_go = total/5

while weeksleft > 0:
if weeksleft > 0:
weeksleft = weeksleft -1
total = total + 50
if monthsleft%1 == 0:
total = total - (to_go)
gone = gone + to_go
if weeksleft == 312:
total = total + (gone/4)
if weeksleft == 104:
total = total + (gone/4)\

print(total)

Thanks!

Jake
towrofterra

Posts: 2
Joined: Mon Apr 08, 2013 9:40 am

### Re: Maths Coding Question

You're never updating monthsleft or to_go values, so they always stay at 13 and 0 respectively. You're not updating gone value when you gain money back at leap year. Finally, your assumption that there are exactly four weeks in a month is untrue, and you're going to accumulate a lot of error over ten years. It is better to use Python's standard library to handle date calculations for you:
Code: Select all
import calendar
from datetime import date, timedelta

total_cash = 0.0
cash_lost = 0.0
start_date = date(year=2013, month=1, day=1)
end_date = date(year=2023, month=1, day=1)
now = start_date

old_week = now.isocalendar()[1]
old_month = now.month
old_year = now.year

while now < end_date:
now += timedelta(days=1)
week = now.isocalendar()[1]

if week != old_week:
total_cash += 50
if now.month != old_month:
lost = 0.2 * total_cash
total_cash -= lost
cash_lost += lost
if now.year != old_year and calendar.isleap(now.year):
regained = 0.25 * cash_lost
total_cash += regained
cash_lost -= regained

old_week = week
old_month = now.month
old_year = now.year

print("It's 2023, and I now have {:.2f} pounds.".format(total_cash))

setrofim

Posts: 288
Joined: Mon Mar 04, 2013 7:52 pm

### Re: Maths Coding Question

Perfect! Thank you so much!
towrofterra

Posts: 2
Joined: Mon Apr 08, 2013 9:40 am