python - 如何在不使用列表或任何其他数据结构的情况下打印最小和最大数量的 n 个随机数
问题描述
程序应该从用户那里读取一个正整数 n 来决定要生成多少个数字。随机数应在区间 [1, 100] 内。然后我应该打印平均值、最小值和最大值。但不使用列表或任何其他数据结构。我设法得到平均值,但我仍然需要得到最小和最大。有什么建议吗?
解决方案
您可以使用内置的 min() 和 max() 函数。这是一些代码,应该很容易解释:
import random
n = 20
# set up the values
smallest = 101
biggest = -1
for i in range(n):
x = random.randint(1,100)
# take the smallest of the new random number and the current smallest
smallest = min(x, smallest)
# take the biggest of the new random number and the current biggest
biggest = max(x, biggest)
print(smallest, biggest)
推荐阅读
- java - 禁用状态栏和导航栏
- kotlin - 重复功能的目的
- ansible - 如何使用 ansible 启动具有不同子网 ID 的多个实例
- php - 如何使用 PHP 将 HTML 表单数组插入 mySQL 中的数据库行
- r - 展开 data.table 的多列包含
- 观察
- python - 为什么整数总是为真
- php - 如果输入字段是动态的并且输入名称总是改变并且它们的数量如何使用PHP将数据插入MySQL?
- css - 为什么浏览器只呈现一些本地安装的字体而不是全部?
- google-calendar-api - 如何根据系列主事件获取所有重复事件
- .htaccess - 我的 htaccess 直通规则改为重定向到 url