1.列表重复运算
- 变量 = 列表 * 数值
fs = [0] * 6 # [0,0,0,0,0,0]
2.列表生成式(推导式)
a = [x for in range(1,6)] # [1,2,3,4,5]
print(a) # [1,2,3,4,5]
b = [x for x in range(1,6) if x % 2 ==0]
print(b) # [2,4]
3.机选双色球代码
# 方法1
import random
list1 = []
n = int(input('请输入购买注数:'))
for x in range(n):
while len(list1) < 6:
num = random.randint(1, 33)
if num not in list1:
list1.append(num)
list1.sort()
list2 = random.randint(1, 16)
list1.append(list2)
for y in list1:
print(f'{y:0>2d}', end=' ')
print()
list1 = []
# 给列表排序,默认升序
# 列表.sort(revers = True) 反转
# 方法2
n = int(input('机选几注:'))
for _ in range(n):
red_ball = [x for x in range(1, 34)]
# 通过random模块的sample函数实现无放回随机抽样,括号里面是抽样总体和抽样数量
list3 = random.sample(red_ball, 6)
# list3 = []
# for x in range(6):
# index = random.randint(0, len(red_ball) - 1)
# list3.append(red_ball.pop(index))
list3.sort()
blue_ball = random.randint(1, 16)
list3.append(blue_ball)
for x in list3:
print(f'{x:0>2d}', end=' ')
print()
4. Josephu环问题
-
有15个男人和15个女人乘船在海上遇险,为了让一部分人活下来,不得不将其中15个人扔到海里,
有个人想了个办法让大家围成一个圈,由某个人开始从1报数,报到9的人就扔到海里面,
他后面的人接着从1开始报数,报到9的人继续扔到海里面,直到将15个人扔到海里。
最后15个女人都幸免于难,15个男人都被扔到了海里。问这些人最开始是怎么站的,哪些位置是男人,
哪些位置是女人。
persons = [True] * 30
num = 0
order = 0
index = 0
while num < 15:
if persons[index]:
order += 1
if order == 9:
persons[index] = False
num += 1
order = 0
index += 1
index %= 30
for person in persons:
print('女' if person else '男', end='')