What I'm trying to do is to make the loop goes to every index in the "investments" list then checks if it's equal to "aMoney" variable or not. if the statement is True then the same index of "investments" in "revenue" list data will be added to "totalMoney" variable and goes back again to do next. My problem is that I want the loop to go back to the False statements to recheck if it's True again and add it to the "totalMoney" variable.
what's happening here is the loop will skip index[0] because 2040 >=/ 3000. but after many loops the condition will be True if we do it again with the new number.
note: Sorting won't work because index[] in first list must go with what same index[] in the second list, no changes.
here is my full code:
numOfProjects = int(7)
aMoney = int(2040)
investments = [3000,2040,3040,5000,3340,4000,7000]
revenue = [500,1000,300,450,2010,650,1500]
totalMoney = int()
totalMoney = aMoney
for j in range(len(investments)):
if(totalMoney >= investments[j]):
totalMoney = revenue[j]
investments[j] 1
revenue[j] 1
totalMoney -= aMoney
print("The profit is $", totalMoney)
the output of this code will be $3960
in papers, it should be $4910 because, first round should be "2040 1000 300 2010 650" = 6000 then we go back at what we left "6000 500 450" = 6950 6950 - 2040 = 4910 I tried my best explaining the idea, hope it's clear
CodePudding user response:
In python, we don't need to initialise int variables as int(number)
, just declaring them with the corresponding value suffices. So instead of aMoney = int(2040)
, just aMoney = 2040
works.
You can use zip
to sort the investments
and revenue
together. Here's a simplified code which does what you need -
initialMoney, currentMoney = 2040, 2040
investments = [3000,2040,3040,5000,3340,4000,7000]
revenue = [500,1000,300,450,2010,650,1500]
data = sorted(zip(investments, revenue))
print(data)
for investment, revenue in data:
if investment <= currentMoney:
currentMoney = revenue
netProfit = currentMoney - initialMoney
print("The profit is $", netProfit)
Output:
[(2040, 1000), (3000, 500), (3040, 300), (3340, 2010), (4000, 650), (5000, 450), (7000, 1500)]
The profit is $ 4910
What you see printed just before profit, is the (investment, revenue)
sorted by investment.