技术需求:开发符合约束规则的简易彩票随机数生成器
简易彩票生成器实现(符合规则)
Got it, let's build this lottery number generator that meets all your specified rules. First, let's recap the requirements to make sure we're on the same page:
生成1至49之间的6个不重复随机数,当出现以下任意一种情况时,需重新生成随机数:
- 包含5个或全部6个“小数”(小数定义为1≤数字<25);
- 包含5个或全部6个“大数”(大数定义为25≤数字≤49);
- 至少5个数字为偶数;
- 至少5个数字为奇数;
- 存在至少3个连续数字(示例:[13,14,15,28,35,49]需重新生成;另一示例:[5,6,7,8,21,38]需重新生成)。
实现思路
The core approach here is straightforward:
- Generate a set of 6 unique random numbers between 1 and 49.
- Validate the set against all 5 rules.
- If the set fails any rule, discard it and generate a new one. Repeat until we get a valid set.
This "generate-and-validate" pattern works perfectly here—since the odds of hitting an invalid set aren't high enough to trap us in a long loop, it's efficient and easy to maintain.
Python代码实现
import random def generate_lottery_numbers(): while True: # 生成6个1-49的不重复随机数,并排序以便后续验证 nums = sorted(random.sample(range(1, 50), 6)) # 验证规则1&2:小数/大数数量不能过多 small_count = sum(1 for num in nums if num < 25) if small_count >= 5 or small_count <= 1: continue # 验证规则3&4:偶数/奇数数量不能过多 even_count = sum(1 for num in nums if num % 2 == 0) if even_count >= 5 or even_count <= 1: continue # 验证规则5:检查是否存在至少3个连续数字 has_consecutive = False for i in range(len(nums) - 2): if nums[i+1] == nums[i] + 1 and nums[i+2] == nums[i] + 2: has_consecutive = True break if has_consecutive: continue # 所有规则都通过,返回结果 return nums # 示例调用 print("符合规则的彩票号码:", generate_lottery_numbers())
代码细节解释
Let's break down what each part does:
- 生成随机数:
random.sample(range(1,50),6)确保我们拿到6个不重复的数字,排序后能更方便地检查连续数。 - 小数/大数校验: 统计小于25的数字数量,如果是5/6个(太多小数)或者1/0个(太多大数),就跳过当前组。
- 偶数/奇数校验: 统计偶数数量,如果是5/6个(太多偶数)或者1/0个(太多奇数),直接重新生成。
- 连续数校验: 遍历排序后的列表,检查是否存在任意三个连续递增1的数字——只要有一组,这个号码就无效。
- 循环直到有效:
while True会持续生成新号码,直到找到完全符合所有规则的一组才返回。
你可以多次调用这个函数,每次都会得到一组符合要求的彩票号码。
内容的提问来源于stack exchange,提问作者Ferit




