Python Forum

Full Version: How many money in 30 days.
You're currently viewing a stripped down version of our content. View the full version with proper formatting.

I need help builing an algorithm where I start with 0.01 cents. Everyday in 30 days, the money is multiplied by 2 so 0.02, 0.04, 0.04, 0.08, if anyone could help me, thanks.
Right now I have this:
def days(d):
amount = d * 2
print(amount)

days(0.01)
days(0.02)
days(0.04)
But I dont want to do it manually.
Please edit your post so that code is included in Python code tags. See here for help.

If you need repetition, then use a for loop. Here is the Python documentation page about it.
import math

def money_days(start, days):
    power2days = math.pow(2, days)
    amount = start * power2days
    print(amount)

money_days(0.01, 30)
'''
The result is: 10737418.24
So, with the starting of 0.01 cents, after 30 days of doubling your money, 
the end result is: 10737418.24 cents or $107374.1824 depending on your currency denomination.
'''
To think another way for doing the math: instead of amount * 2 each time, do a power 2 of 30 times, which in python, you can use math.pow(x, y), or in your case: math.pow(2, 30); then multiply by the starting amount 0.01 (dollar or cents), the final result is what you want.
def days(d):
    amount = d * 2
    print(amount)

days(0.01)
days(0.02)
days(0.04)

Thank you so much, one question, what does the "import" do?
You could also do it with a recursive function (a function that calls itself). You know that the day d, the amount will be twice the amount of day d-1, until you reach day 1 where the amount is 0.01. So:

def days(d):
    if d <= 1:
        return 0.01
    else:
        return days(d-1) * 2

while True:
    d = int(input("number of days (0 to stop): "))
    if d == 0:
        break
    else:
        print("Total amount: " + str(days(d)))
The inconvenient of a recursive function is that it is much slower to calculate the result, compared to a direct calculation like the power of 2. The advantage is that is is usually simpler to write and if the formula to go from day d-1 to day d is not simple, you may have some difficulties to find a way to calculate it easily.

As an exercise, consider that you have 50 the first day, that you double each day but you need to subtract 35 at the end of each day for your food. Finding the formula which will give you the result is not so trivial.