【问题标题】:How to calculate number of zeroes from 1 to a user given number and calculate time it took?如何计算从 1 到用户给定数字的零数并计算所花费的时间?
【发布时间】:2019-09-12 21:46:47
【问题描述】:

所以,基本上,我需要计算从 1 到用户给定数字的零数。我需要向他们询问一个数字,在函数中使用 for 循环来计算该数字中零的数量,将其打印回给他们,然后使用 time() 函数,打印计算所需的时间.所需的输出应如下所示:

你想把零数到什么数字? 10000

The number of zeros written from 1 to 10000 is 2893.
This took 0.0105922222137 seconds.

-这是我目前所拥有的,它非常迷失方向,因为我试图同时处理不同的部分,我意识到这可能不是处理它的最佳方式

 from time import time


 start_time =time()

stop_time = time()
elapsed = stop_time - start_time


def Count():
    i = 0'
    count = 0'
    for i in range(1,):
       if i % 10 is 0
            i = i + 1




x =
Num1 = input("What number do you want to count zeros to?: ")
print "The number of zeros written from 1 to {} is {}".format(Num1, x)

如果有人能提供帮助,将不胜感激。

【问题讨论】:

  • 欢迎来到 StackOverflow。请按照您创建此帐户时的建议阅读并遵循帮助文档中的发布指南。 Minimal, complete, verifiable example 适用于此。在您发布 MCVE 代码并准确说明问题之前,我们无法有效地帮助您。我们应该能够将您发布的代码粘贴到文本文件中并重现您指定的问题。 StackOverflow 不是设计、编码、研究或教程资源。
  • 您的行顺序错误。如果你想计算时间,那么你应该在开始和结束时获得时间,但你在开始时都需要两次。如果你得到Num1 然后在range(Num1) 中使用它。数字可能有很多零,所以使用i % 10 是没用的。更好地将数字转换为字符串并在此字符串中计数字符“0”。
  • 考虑以log base 10的差异为起点
  • @furas,不完全正确。您可以在每个号码上使用while 循环,并使用% 结合num //= 10 从号码中弹出数字
  • @C.Nivs 你是对的,代码需要额外的while 循环。我想知道它是否会比转换为字符串运行得更快,但我不会对其进行测试:)

标签: python python-2.7 loops for-loop time


【解决方案1】:

这个问题的主要技巧是从计算 0 的数量开始,然后继续计算时间。将程序结构想象为:

  • 开始计时器
  • 计数 0
  • 结束计时器
  • 显示输出

所以要计算 0,我们可能会在范围内使用循环,这只是一个从开始到结束的数字列表,所以

range(0, 10)

真的只是

[0,1,2,3,4,5,6,7,8,9]

因此,我们可以从开始(在本例中为 0)循环到结束(在本例中为 10000),这可能看起来像:

end = 10000
count = 0

for number in range(1, end + 1):
    count += str(number).count("0")

然后,我们可以使用时间库添加一个计时器,并打印结果,所以我们的代码如下所示:

import time
start_time = time.time()
end = 10000
count = 0

for number in range(1, end + 1):
    count += str(number).count("0")

print("The number of zeros written from 1 to " + str(end) + " is " + str(count) + ".")
print("This took %s seconds." % (time.time() - start_time))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-09-05
    • 1970-01-01
    • 2016-09-12
    • 1970-01-01
    • 2020-06-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多