容器-----列表
1.课前预习
把一颗色子摇6000次,统计每一面出现的次数
import random
fs = [0] * 6 # 列表的重复
for _ in range(6000):
face = random.randint(1, 6)
fs[face - 1] += 1
print(fs)
for i in range(1, 7):
print(f'{i}点出现了{fs[i - 1]}次')
2.创建列表
列表的生成式(推导式) >-----创建列表的一种字面量语法
a = [x for x in range(1, 101)]
print(a)
b = [x for x in range(0, 101, 2)]
print(b)
c = [x for x in range(1, 101) if x % 15 == 0]
print(c)
d = [x ** 2 for x in range(1, 11)]
print(d)
3.练习
1).CRAPS赌博游戏:
玩家摇两颗色子,如果第一次摇出了7点或11点,玩家胜;
如果摇出了2点、3点或12点,庄家胜;
其他情况不分胜负,游戏继续。
玩家重新摇色子,如果摇出了第一次摇的点数,玩家胜;
如果摇出了7点,庄家胜;
其他情况游戏继续,直到分出胜负。
n = int(input('机选几注:'))
for _ in range(n):
# 方法一
import random
selected_balls = []
while len(selected_balls) < 6:
red_ball = random.randint(1, 33)
if red_ball not in selected_balls:
selected_balls.append(red_ball)
selected_balls.sort()
blue_ball = random.randint(1, 16)
selected_balls.append(blue_ball)
print(selected_balls)
# 方法二
import random
red_ball = [x for x in range(1, 34)]
selected_balls = []
for _ in range(6):
index = random.randint(0, len(red_ball) - 1)
selected_balls.append(red_ball.pop(index))
# 给列表元素排序(默认升序),列表.sort()
# 从大到小:列表.sort(reverse = True) reverse:反转
selected_balls.sort()
blue_ball = random.randint(1, 16)
selected_balls.append(blue_ball)
# 格式化输出
# 整数:d 2d:表示占两位
# 0<:后面补0 0>:前面补0 1<:后面补1 1>:前面补1
# 查看函数参数的含义:shift + F1
for ball in selected_balls:
print(f'{ball:0>2d}', end=' ')
print()
Josephu环问题
有15个男人和15个女人乘船在海上遇险,为了让一部分人活下来,
不得不将其中15个人扔到海里,有个人想了个办法让大家围成一个圈,
由某个人开始从1报数,报到9的人就扔到海里面,他后面的人接着从1开始报数,
报到9的人继续扔到海里面,直到将15个人扔到海里。
最后15个女人都幸免于难,15个男人都被扔到了海里。
问这些人最开始是怎么站的,哪些位置是男人,哪些位置是女人。
people = [True] * 30
count, index, num = 0, 0, 0
while count < 15:
if people[index]:
num += 1
if num == 9:
people[index] = False
count += 1
num = 0
index += 1
index %= 30
for people in people:
# 三元条件运算(people为真,取if前的值;people为假,取else后的值)
print('女' if people else '男', end='')
print()