Python script that increases a number by a percent and then with a new number till goal

Question:

I found this problem and wanted to try to execute, but got stuck:

Compile a program that allows you to determine how many days will be enough for 200 something if consumed on the first day 5 tons, but every next day 20% more than the previous day.

In Python, using loop operators, lists and
functions.

I tried with the def function, but I don’t know if it’s correct and I don’t know how to get it so that when it increases by 20%, the new number increases by 20%, so all the time with new numbers until it reaches 200

def day():
    x=5
    x += (x * 20/100)
    print(x)
day()

it is just a half, i know.

Asked By: Pmileika

||

Answers:

The solution which you’re trying to implement, is very close, but you’re not actually adding the values from day. You want something like the following:

def day(x):
    return x + (x * 20/100)

x = 5
currentSum = x
day = 1
while(currentSum < 200): # Loop until the amount consumed is more than 200
    x = day(x)
    currentSum += x
    day += 1

print(day)

Note, there is a faster mathematical solution, but it is not necessary for this problem since all the numbers are fairly small.

Answered By: QWERTYL

You are calling the function a single time, basically X is incrementing once and then not being referenced again. To increment X until you reach a value >= 200, you would need to use a while loop. Code could look like this:

x = 5
dayscount = 1
while x < 200:
   print(x)
   print(dayscount)
   dayscount = dayscount + 1
   x = x * (1+(20/100))

you dont necessarily need to define within a function either, but if you did, you would need to define x outside the function and make it a global variable.

Answered By: philbeet

Declaring Needed Variables

numberOfDays = 0 
totalTons = 200
dayTonsUsed = 5 

Consuming the tons and modifying the variables

while (totalTons > 0):
    totalTons -= dayTonsUsed
    dayTonsUsed *= 1.2 # Adding extra 20% of consumption for the next day 
    numberOfDays += 1 

Getting total days

print(f"Number of days needed {numberOfDays} days")
Answered By: ahmedsultan

with recursion it could be done this way:

def day(n, x=5):
    return 1 + day(n-x, x*1.2) if n>0 else 0

day(200)  # 13
Answered By: SergFSM