Python编程:函数、随机数与标准库的深度探索
立即解锁
发布时间: 2025-08-29 10:27:49 阅读量: 8 订阅数: 14 

### Python编程:函数、随机数与标准库的深度探索
#### 1. Python内置的max和min函数
在Python中,许多常见任务所需的功能已经内置。例如,`max`和`min`函数可以分别确定两个或多个参数中的最大值和最小值。这两个函数也可以接收可迭代参数,如列表或字符串。使用内置函数或Python标准库模块中的函数,而不是自己编写代码,可以减少开发时间,提高程序的可靠性、可移植性和性能。Python内置函数和模块列表可查看:[https://docs.python.org/3/library/index.html](https://docs.python.org/3/library/index.html) 。
示例代码:
```python
In [6]: max('yellow', 'red', 'orange', 'blue', 'green')
Out[6]: 'yellow'
In [7]: min(15, 9, 27, 14)
Out[7]: 9
```
#### 2. 随机数生成
##### 2.1 模拟掷六面骰子
可以通过Python标准库的`random`模块引入随机性。以下代码模拟掷六面骰子10次:
```python
In [1]: import random
In [2]: for roll in range(10):
...: print(random.randrange(1, 7), end=' ')
...:
4 2 5 5 4 6 4 6 1 5
In [3]: for roll in range(10):
...: print(random.randrange(1, 7), end=' ')
...:
4 5 4 5 1 4 1 4 6 5
```
`randrange`函数生成从第一个参数值到第二个参数值(不包括)之间的整数。
##### 2.2 模拟掷六面骰子6000000次
为了验证`randrange`生成的整数是随机的,且每个数字出现的概率相等,以下脚本模拟掷六面骰子6000000次:
```python
# fig04_01.py
"""Roll a six-sided die 6,000,000 times."""
import random
# face frequency counters
frequency1 = 0
frequency2 = 0
frequency3 = 0
frequency4 = 0
frequency5 = 0
frequency6 = 0
# 6,000,000 die rolls
for roll in range(6_000_000): # note underscore separators
face = random.randrange(1, 7)
# increment appropriate face counter
if face == 1:
frequency1 += 1
elif face == 2:
frequency2 += 1
elif face == 3:
frequency3 += 1
elif face == 4:
frequency4 += 1
elif face == 5:
frequency5 += 1
elif face == 6:
frequency6 += 1
print(f'Face{"Frequency":>13}')
print(f'{1:>4}{frequency1:>13}')
print(f'{2:>4}{frequency2:>13}')
print(f'{3:>4}{frequency3:>13}')
print(f'{4:>4}{frequency4:>13}')
print(f'{5:>4}{frequency5:>13}')
print(f'{6:>4}{frequency6:>13}')
```
运行结果示例:
```plaintext
Face Frequency
1 998686
2 1001481
3 999900
4 1000453
5 999953
6 999527
```
此程序使用嵌套控制语句(`for`语句中嵌套`if...elif`语句)来确定每个骰子面出现的次数。注意,`range(6_000_000)`使用了下划线分隔符,以提高可读性,而`range(6,000,000)`会被Python视为调用`range`函数,传入三个参数6、0和0。
##### 2.3 为随机数生成器设置种子以实现可重复性
`randrange`实际上生成的是伪随机数,基于一个称为种子的数值进行内部计算。每次启动新的交互式会话或执行使用`random`模块函数的脚本时,Python内部使用不同的种子值。在调试使用随机生成数据的程序时,可以使用`random`模块的`seed`函数设置种子,使`randrange`从指定的种子开始计算伪随机数序列。
示例代码:
```python
In [4]: random.seed(32)
In [5]: for roll in range(10):
...: print(random.randrange(1, 7), end=' ')
...:
1 2 2 3 6 2 4 1 6 1
In [6]: for roll in range(10):
...: print(random.randrange(1, 7), end=' ')
...:
1 3 5 3 1 5 6 4 3 5
In [7]: random.seed(32)
In [8]: for roll in range(10):
...: print(random.randrange(1, 7), end=' ')
...:
1 2 2 3 6 2 4 1 6 1
```
由于代码块[4]和[7]使用了相同的种子(32),代码块[5]和[8]产生相同的结果。代码块[6]生成不同的值,因为它继续了代码块[5]开始的伪随机数序列。
#### 3. 案例研究:机会游戏“双骰子赌博”
此部分模拟流行的骰子游戏“双骰子赌博”(craps)。游戏规则如下:掷两个六面骰子,计算两个朝上的面的点数之和。如果第一次掷出的和为7或11,则获胜;如果和为2、3或12,则失败;如果和为4、5、6、8、9或10,则该和成为“点数”,需要继续掷骰子,直到再次掷出该点数则获胜,掷出7则失败。
以下是模拟该游戏的代码:
```python
# fig04_02.py
"""Simulating the dice game Craps."""
import random
def roll_dice():
"""Roll two dice and return their face values as a tuple."""
die1 = random.randrange(1, 7)
die2 = random.randrange(1, 7)
return (die1, die2) # pack die face values into a tuple
def display_dice(dice):
"""Display one roll of the two dice."""
die1, die2 = dice # unpack the tuple into variables die1 and die2
print(f'Player rolled {die1} + {die2} = {sum(dice)}')
die_values = roll_dice() # first roll
display_dice(die_values)
# determine game status and point, based on first roll
sum_of_dice = s
```
0
0
复制全文
相关推荐










