Python单词Prob Issu

2024-10-03 13:20:51 发布

您现在位置:Python中文网/ 问答频道 /正文

这个词的问题是:产生一个项目只需要2分7秒。不幸的是,143件产品生产完成后,制造商必须冷却5分13秒才能继续生产。编写一个程序,计算制造一定数量的产品所需的时间。你知道吗

测试编号为1340项。你知道吗

numItems = 1340
produceitem = 2 * 60 + 7  #2 minutes and 7 seconds
cooldown = 5 * 60 + 13 #5 minutes and 13 seconds
items_before_delay = 143
productiontime = 0

if numItems <= 143:
    productiontime = produceitem * numItems
if numItems > 143:
    productiontime = (produceitems * numItems) - (numItems / items_before_delay * cooldown) 
print str(productiontime) + "seconds"

测试编号的输出应该是172997秒,但是我的程序输出它为167363秒。你知道吗

有人能告诉我我能做些什么来改进这个吗?你知道吗


Tags: and项目程序ifitems编号secondsdelay
1条回答
网友
1楼 · 发布于 2024-10-03 13:20:51

你在减去冷却时间,而不是加上它。就这样。你知道吗

所以,改变这个:

productiontime = (produceitems * numItems) - (numItems / items_before_delay * cooldown) 

…对此:

productiontime = (produceitems * numItems) + (numItems / items_before_delay * cooldown) 

然而,当我们在这里时:

  • 您定义了produceitem,但使用了produceitems。如果这真的奏效了,那可能是因为您在交互式解释器中很幸运,已经定义了produceitems。你知道吗
  • 如果要定义一个常量items_before_delay,不要直接使用143,使用items_before_delay。你知道吗
  • 不要做if a <= b:然后if a > b:;只要把第二个改成else:。你知道吗
  • 实际上,您根本不需要if。如果numItems <= 143(numitems / items_before_delay * cooldown)将是0,那么第二个版本仍然会给出正确的答案。你知道吗
  • 除非您处理的是非常旧的Python版本,否则通常最好显式使用//来截断整数除法,而不是/。这意味着您的代码仍然可以在Python3.x中工作,或者如果有人执行__future__语句,等等——更重要的是,这意味着人们可以阅读和理解您的代码,而不必猜测它是用于2.x还是3.x
  • 你的名字要有一致的风格。items_before_delay遵循PEP8的建议,但numItems没有。你知道吗
  • 在设置变量之前,不需要“声明”像productiontime这样的变量。你知道吗
  • 连接两个字符串不会在两个字符串之间产生空格,而且您可能不希望172997seconds没有空格。你知道吗
  • 尽量避免写太长的行,以适应80列。即使你认为没有人关心老式的文本编辑器,像StackOverflow这样的新型web界面仍然是个问题。(没有人喜欢不必要的水平滚动条。)

所以:

num_items = 1340
produce_item = 2 * 60 + 7  #2 minutes and 7 seconds
cooldown = 5 * 60 + 13 #5 minutes and 13 seconds
items_before_delay = 143

total_cooldown = num_items // items_before_delay * cooldown
production_time = (produce_item * num_items) + total_cooldown
print '{} seconds'.format(production_time)

相关问题 更多 >