【发布时间】:2011-02-14 08:38:52
【问题描述】:
这个问题/解决方案让我提出了另一个相关问题here - 非常感谢您的帮助!
根据最初的反馈更新了下面的当前代码
我是 Python 的新手(这是我的第二个程序)。我目前正在使用麻省理工学院的开放课件来介绍使用 Python Academic Earth videos 的 CS,并且我正在研究问题集 1 Viewable Here。我已经创建了这个程序,该程序在 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
如果您在此新代码中看到任何其他内容,请告诉我!
非常感谢帮助我走到今天这一步的人。
【问题讨论】:
-
有一个关于代码审查的网站。 codereview.stackexchange.com
标签: python