python - 如何将两个程序合并为一个程序?

标签 python python-3.x

我正在尝试找出 1000 匹马平均需要多少秒的方法。我想出了如何求 1000 个随机整数的平均值以及一匹马完成比赛的时间。我不明白如何将它们一起实现。

编辑:任何使我的代码更整洁的建议都可以!

编辑2:抱歉,可能不清楚。 A 部分是找出 10-20 范围内的 1000 个随机整数的平均值,应该在 15 左右。B 部分是看看一匹马完成一场比赛需要多少秒,平均时间为 450-500 秒。 C 部分应该模拟 1000 场比赛,但同时也求出平均值。 *

这是我的代码:

#Main Program
#This program will find the average of 1000 random numbers.
from random import randrange

def main():
  numbers = []
  for count in range(1000):
     number = random.randrange(10,21)
     numbers.append(number)
  print('{} is the average of 1000 random numbers from the range 10 to 20.'.format(sum(numbers)/len(numbers)))

main()

#Part B
#This program will similate one horse race.
from random import randrange

def race():
 goal = 10560 #2 miles is 10,560 feet
 current_position = 0
 elapsed_seconds = 0
 while current_position <= goal:
  elapsed_seconds += 1
  current_position += randrange(4,41)
print('{} seconds for one horse to finish the race.'.format(elapsed_seconds))

race()

#Part C
#This program will find the average of 1000 horse races.
def races():
 numbers = []
 goal = 10560
 current_position = 0
 elapsed_seconds = 0

最佳答案

我没有完全遵循你的计划,但我有一些想法。

您可能需要做的一件事是将race()模块嵌入到races()中,这样当您调用races()时就会执行race()。要将数据发送回 races() 模块,请将 print() 函数替换为返回函数(请记住,返回函数会终止循环),并将类似以下代码的代码放入 races() 中:

race_value = race()
numbers.append(race_value)

关于python - 如何将两个程序合并为一个程序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52693796/

相关文章:

python - 在 Grumpy 中安装一个 python 包

python - 删除组合框项目的按钮

python:如何将列表中的每个值与另一个列表中的所有值相乘

python - SymPy 无法计算此矩阵的特征值

python - 您可以(在 python 脚本内部)将另一个脚本排入队列以在第一个脚本完全退出后运行吗?

python - 创建可以跨流程比较的变量

python - 解决 python 3 与 python 2 中的 map 函数问题

python - $addToSet,以及更新其他字段?

python - 如何在代码中停止 autopep8 未安装的消息

python - 如何为 AWS Lambdas 安装 Numpy 和 Pandas?