每日一练:组合不重复的四位数字

在这里插入图片描述

问题:有四个数字“1、2、3、4”,能组成多少个互不相同且无重复数字的四位数?各是多少?

程序分析

  可填在千位、百位、十位、个位的数字都是1、2、3、4。组成所有的排列后再去掉不满足条件的排列。

实现方法1

  1)使用四层嵌套循环,每一层循环选择一个数字。
  2)在循环过程中,判断所选的四个数字是否互不相同,如果是则输出这个四位数。

# 循环遍历所有可能的组合
count = 0
for i in range(1, 5):  # 第一个数字
    for j in range(1, 5):  # 第二个数字
        for k in range(1, 5):  # 第三个数字
            for l in range(1, 5):  # 第四个数字
                # 判断四个数字是否互不相同
                if i != j and i != k and i != l and j != k and j != l and k != l:
                    # 组合成一个四位数并输出
                    result = i * 1000 + j * 100 + k * 10 + l
                    count += 1
                    print(f'第{count}个数是:{result}')

实现方法2

  使用 itertools 模块中的 permutations 函数来生成所有可能的排列,然后筛选满足条件的结果。

from itertools import permutations

# 四个数字
digits = [1, 2, 3, 4]

# 生成所有可能的排列
permutation_list = permutations(digits)

count = 0
# 遍历排列并输出满足条件的四位数
for perm in permutation_list:
    result = perm[0] * 1000 + perm[1] * 100 + perm[2] * 10 + perm[3]
    count += 1
    print(f'第{count}个数是:{result}')

实现方式3

  递归的思路是从左到右依次确定每一位的数字,并在确定了前几位的情况下递归地确定后面的位数。

def generate_four_digit_numbers(digits, current_number, used_digits, count):
    """
    递归生成所有可能的四位数,并输出格式化的结果。

    Parameters:
    - digits: 可选数字列表
    - current_number: 当前正在生成的数
    - used_digits: 已经使用过的数字列表
    - count: 当前是第几个满足条件的数

    Returns:
    - count: 更新后的计数值
    """
    if len(used_digits) == 4:
        # 输出格式化的结果
        print(f"第{count}个数是:{current_number}")
        return count + 1

    new_count = count
    for digit in digits:
        if digit not in used_digits:
            new_number = current_number * 10 + digit
            new_used_digits = used_digits + [digit]
            # 递归调用,更新 count
            new_count = generate_four_digit_numbers(digits, new_number, new_used_digits, new_count)

    return new_count

# 四个数字
digits = [1, 2, 3, 4]

# 调用递归函数,初始 count 为 1
generate_four_digit_numbers(digits, 0, [], 1)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

snail哥

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值