is it possible to recheck an index in a list in the same loop again? python

Question:

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

Asked By: F00

||

Answers:

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.

Answered By: Jay
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.