Python初学者.这个Python代码是否尽可能高效?
发布时间:2020-12-20 12:17:45 所属栏目:Python 来源:网络整理
导读:这个问题/解决方案让我想到另一个相关的问题 here – 帮助将不胜感激! 根据初步反馈更新了以下当前代码 我是Python的新手(这是我的第二个程序).我目前正在使用麻省理工学院的开放课件使用Python Academic Earth videos来介绍CS,我正在研究问题集1 Viewable
这个问题/解决方案让我想到另一个相关的问题
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 如果您在此新代码中看到任何其他内容,请告诉我们! 非常感谢那些帮助我实现这一目标的人. 解决方法print "x: " + str(x) 应该替换为: print "x:",x 这是打印的特例. 将循环更改为: for month in xrange(1,12+1): 删除第一个循环的检查,然后将余额设置为remainingBalance作为结束. 因为您手动增加月份,所以每次都打印错误的值. 如果你的效率和执行效率一样,那你就担心too soon了.如果你的意思是复制代码,你会在循环之前不必要地复制数学.结合以上内容: 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:',month print 'Minimum monthly payment:',minPayment print 'Principle paid:',principalPaid print 'Remaining balance:',remainingBalance balance = remainingBalance (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |