gpt4 book ai didi

python 初学者。这段 Python 代码是否尽可能高效?

转载 作者:太空宇宙 更新时间:2023-11-03 12:29:25 24 4
gpt4 key购买 nike

这个问题/解决方案让我想到了另一个相关问题 here - 将不胜感激!

根据初步反馈更新了下面的当前代码

我是 Python 的新手(这是我的第二个程序)。我目前正在使用麻省理工学院的开放课件来了解使用 Python 的 CS Academic Earth videos我正在研究问题集 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

关于 python 初学者。这段 Python 代码是否尽可能高效?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4990159/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com