"""练习 17:枚举 0~9 中不重复数字组成的三位偶数,并用乘法原理验证。 学习说明: - 三重循环分别选择百位、十位、个位;百位从 1 开始,保证数是三位数。 - 偶数的个位只能是 0、2、4、6、8;三个位置还必须互不相同。 - 乘法原理计算时分个位为 0 和个位非 0 两种情况,避免把可选数字数错。 - 两种独立方法都求出数量,最后输出以便核对。 """ count_by_enumeration = 0 # 逐一枚举三个数位的所有候选组合。 for hundreds in range(1, 10): for tens in range(10): for ones in (0, 2, 4, 6, 8): if hundreds != tens and hundreds != ones and tens != ones: count_by_enumeration += 1 # 个位为 0:9 种百位 × 8 种十位。 # 个位为 2、4、6、8:4 × 8 种百位 × 8 种十位。 count_by_rule = 9 * 8 + 4 * 8 * 8 print("enumeration:", count_by_enumeration) print("counting principle:", count_by_rule)