red_balls = list(range(1, 34)) blue_balls = list(range(1, 17)) n = 0 # 计算所有红球组合 red_ball_combinations = list(itertools.combinations(red_balls, 6)) # 计算每个红球组合加上一个蓝球的所有组合,并且筛选符合条件的组合 selected_combinations = [] for red_ball_combination in red_ball_combinations: if set([4, 8, 17, 20, 22, 27]).intersection(set(red_ball_combination)): pass else: for blue_ball in blue_balls: combination = list(red_ball_combination) + [blue_ball] selected_combinations.append(combination) # 输出结果 for combination in selected_combinations: hongqiu = combination[:6] lanqiu = combination[-1] max_consecutive = 1 # 遍历列表,计算最大相邻数的个数 zdxl = 1 for i in range(len(hongqiu) - 1): if hongqiu[i + 1] == hongqiu[i] + 1: zdxl += 1 if zdxl > max_consecutive: max_consecutive = zdxl else: zdxl = 1 # 输出结果 # print("最大相连数个数:", max_consecutive) if max_consecutive <= 3: n += 1 print('红球:', hongqiu, '篮球:', lanqiu,'第',n,'组')把这个代码综合简洁一下
时间: 2024-03-25 16:41:40 浏览: 131
可以将计算所有红球组合和计算符合条件的组合的部分合并,并且使用列表推导式简化代码:
```python
import itertools
red_balls = list(range(1, 34))
blue_balls = list(range(1, 17))
n = 0
selected_combinations = [list(red_ball_combination) + [blue_ball] for red_ball_combination in itertools.combinations(red_balls, 6)
if not set([4, 8, 17, 20, 22, 27]).intersection(set(red_ball_combination))
for blue_ball in blue_balls]
for i, combination in enumerate(selected_combinations):
hongqiu = combination[:6]
lanqiu = combination[-1]
max_consecutive = 1
zdxl = 1
for j in range(len(hongqiu) - 1):
if hongqiu[j + 1] == hongqiu[j] + 1:
zdxl += 1
if zdxl > max_consecutive:
max_consecutive = zdxl
else:
zdxl = 1
if max_consecutive <= 3:
n += 1
print(f"红球: {hongqiu}, 篮球: {lanqiu}, 第{n}组")
```
这样代码就更加简洁明了了。
阅读全文