这个问题/解决方案让我想到了另一个相关问题here https://stackoverflow.com/questions/4997859/calculate-a-running-total-during-a-for-loop-python- 帮助将不胜感激!
根据初始反馈更新了下面的当前代码
我对 Python 是全新的(这是我的第二个程序)。我目前正在使用 MIT 的开放课件来了解使用 Python 进行 CS 的介绍学术地球视频 http://www.academicearth.org/courses/introduction-to-computer-science-and-programming我正在研究问题集 1可以在这里查看 http://mit600.mit.edu/blog/problem-sets/problem-set-1/。我已经创建了这个程序,该程序在 12 个月内成功地重新创建了“测试用例 1”(不包括“结果”部分......仍在研究中),但我的问题是,以下(我的)代码是否尽可能高效?我觉得我在重复自己,而这可能没有必要。 :
原始代码:
balance = float(raw_input("Outstanding Balance: "))
interestRate = float(raw_input("Interest Rate: "))
minPayRate = float(raw_input("Minimum Monthly Payment Rate: "))
interestPaid = round((interestRate/12.0)*balance, 2)
minPayment = round(minPayRate*balance, 2)
principalPaid = round(minPayment-interestPaid, 2)
remainingBalance = round(balance-principalPaid, 2)
month = 1
while month < 12 :
if month > 1 :
balance = remainingBalance
interestPaid = round((interestRate/12.0)*balance, 2)
minPayment = round(minPayRate*balance, 2)
principalPaid = round(minPayment-interestPaid, 2)
remainingBalance = round(balance-principalPaid , 2)
month = month+1
print 'Month: ' + str(month)
print 'Minimum monthly payment: ' + str(minPayment)
print 'Principle paid: ' + str(principalPaid)
print 'Remaining balance: ' + str(remainingBalance)
当前代码
balance = float(raw_input("Outstanding Balance: "))
interestRate = float(raw_input("Interest Rate: "))
minPayRate = float(raw_input("Minimum Monthly Payment Rate: "))
for month in xrange(1, 12+1):
interestPaid = round(interestRate / 12.0 * balance, 2)
minPayment = round(minPayRate * balance, 2)
principalPaid = round(minPayment - interestPaid, 2)
remainingBalance = round(balance - principalPaid, 2)
print 'Month: %d' % (month,)
print 'Minimum monthly payment: %.2f' % (minPayment,)
print 'Principle paid: %.2f' % (principalPaid,)
print 'Remaining balance: %.2f' % (remainingBalance,)
balance = remainingBalance
如果您在这个新代码中看到任何其他内容,请告诉我!
非常感谢那些帮助我走到这一步的人。