【问题标题】:Printing as many numbers as possible in 9 seconds then a "-1" at the 10th second在 9 秒内打印尽可能多的数字,然后在第 10 秒打印“-1”
【发布时间】:2020-10-16 11:00:06
【问题描述】:

所以,我有兴趣在 9 秒内打印尽可能多的数字,然后在第 10 秒打印 -1。我有一个 while 循环每 10 秒打印 -1 和一个 while 循环每 9 秒打印 0 到 10 之间的任何随机数。我正在做this

我的问题有两个:

  1. 我不知道如何创建一个可以在 9 秒内打印尽可能多的数字(取决于计算速度)的循环
  2. 我不知道如何将它与循环放在一起以每 10 秒打印一次 -1。

非常感谢大家!

【问题讨论】:

  • 作弊。以字符串开头:“1 2 3 4 ... 99 100”。尽可能多地打印该字符串,然后打印-1。 :)
  • 在第 9 秒到第 10 秒之间你应该做什么?

标签: python-3.x random numbers


【解决方案1】:

您可以为此目的使用 python 的time 模块。检查以下代码以供参考:

import time
import random

# Time for which you want the loop to run
time_to_run = 25
# Stores the future time when the loop should stop
loop_for_x_seconds = time.time() + time_to_run
start_time = time.time()
multiplier = 1 # print -1 at 10 second, increment it, so next one will be at 10*multiplier = 20 and so on...

# Loop until current time is less than the time we want our loop to run
while time.time() < loop_for_x_seconds:
    # The below condition will help print -1 after about every 10s
    if (time.time()-start_time)>=10*multiplier:
        print(-1)
        multiplier+=1
    # Commented below just for purpose of showing output of -1 every 10s. Uncomment and use to get random ints printed
    #else:
        #print(random.randint(1,10))  

输出:

-1
-1

上面的代码大约每 10 秒打印一次-1。我本可以做到 (time.time()-start_time)%10==0 ,但这种情况很少会被评估为 True。

所以,我选择了 (time.time()-start_time)&gt;=10*multiplier 。此代码将在每 10 秒后打印-1(相差几毫秒)。

您不需要使用图片中显示的time.sleep(10),因为这就像暂停循环一样。但是,您希望每 10 秒连续运行一次循环打印 -1 并在其他时间打印随机整数。所以上面的代码可以满足你的目的。

希望这会有所帮助!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-09-22
    • 2013-03-13
    • 1970-01-01
    • 2021-11-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-17
    相关资源
    最近更新 更多