我想要做的是讓回圈轉到“投資”串列中的每個索引,然后檢查它是否等于“aMoney”變數。如果陳述句為真,則“收入”串列資料中“投資”的相同索引將添加到“totalMoney”變數并再次回傳以執行下一步。我的問題是我希望回圈回傳到 False 陳述句以重新檢查它是否再次為 True 并將其添加到“totalMoney”變數。
這里發生的是回圈將跳過索引 [0],因為 2040 >=/ 3000。但是在許多回圈之后,如果我們用新數字再次執行,條件將為 True。
注意:排序不起作用,因為第一個串列中的 index[] 必須與第二個串列中的相同 index[] 一致,沒有變化。
這是我的完整代碼:
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)
此代碼的輸出將是 $3960
在論文中,它應該是 4910 美元,因為,第一輪應該是“2040 1000 300 2010 650”= 6000 然后我們回到我們剩下的“6000 500 450”= 6950 6950 - 2040 = 4910 我試過我最好解釋這個想法,希望它很清楚
uj5u.com熱心網友回復:
在 python 中,我們不需要將 int 變數初始化為int(number),只需將它們宣告為相應的值即可。所以不是aMoney = int(2040),只是aMoney = 2040作業。
您可以使用和一起zip排序。這是一個簡化的代碼,可以滿足您的需要 -investmentsrevenue
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)
輸出:
[(2040, 1000), (3000, 500), (3040, 300), (3340, 2010), (4000, 650), (5000, 450), (7000, 1500)]
The profit is $ 4910
您在利潤之前看到的列印內容是(investment, revenue)按投資排序的。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/534256.html
上一篇:Mongoosev6.2.7新的Model.save()方法無法正常作業在try-catch中嘗試了promise、回呼和異步等待,但沒有任何效果
下一篇:在do嵌套回圈中打開MP
