There are four numbers 1, 2, 3, and 4, which can form multiple three-digit numbers, and output the three-digit numbers that are different from each other and have no repeated numbers

There are four numbers 1, 2, 3, 4, how many different three-digit numbers can be formed without repeating numbers

  #include "stdio.h"
main()
{
    int i,j,k,sum=0;
    for(i=1;i<=4;i++)
        for(j=1;j<=4;j++)
            for(k=1;k<=4;k++)
            {
                if(i!=j&&i!=k)
                {
                    printf("%d%d%d ",i,j,k);
                    sum++;
                }
            }
    printf("\n");
    printf("sum=%d",sum);
}

python

1 def output():
2     count = 0
3     for i in range(1,5):
4         for j in range(1, 5):
5             for k in range(1, 5):
6                 if i==j or i==k or j==k:
7                     continue
8                 yield str(i)+str(j)+str(k)

train of thought

The first layer of loop: to determine the number of hundreds, in order to prevent repetition, the number used is taken out of the list. Tens and ones take values ​​from the rest of the list.

The second layer of loop: to determine the ten digits, in order to prevent repetition, the used numbers are taken out of the list. The ones place takes the value from the rest of the list.

The third layer of loop: loop the remaining list to determine the single digit.

# 复杂实现方法
tar = [1, 2, 3, 4]
count = 0  # 结果计数
for i in range(len(tar)):  #最外层循环,确定百位数字
    t1 = tar.copy()  # 操作临时变量,防止改变原始tar的值,影响下次循环
    x = str(t1.pop(i))  # 取出百位数字
    for j in range(len(t1)):  # 循环剩余列表,确定十位和个位
        t2 = t1.copy()  # 操作临时变量,防止改变t1的值,影响下次循环
        y = str(t2.pop(j))  # 取出十位数字
        for k in range(len(t2)):  # 循环剩余列表,确定个位
            print(x + y + str(t2[k]), end='  ')  #将百位十位和个位拼接,得到一个结果
            count += 1  #结果计数+1
    print('')  # 百位相同的结果显示为一行,百位数字改变的时候换行
print('最终结果为:%s个' % count)
 
 
# 复杂实现方法二
tar = [1, 2, 3, 4]
count = 0  # 结果计数
for i in range(len(tar)):
    x = str(tar.pop(i))  # 取出百位数字
    for j in range(len(tar)):
        y = str(tar.pop(j))  # 取出十位数字
        for k in range(len(tar)):
            print(x + y + str(tar[k]), end='  ')  #将百位十位和个位拼接,得到一个结果
            count += 1  #结果计数+1
        tar.insert(j, int(y))  # 将拿出的十位数字放回原始列表,防止影响下次循环
    tar.insert(i, int(x))  # 将拿出的百位数字放回原始列表,防止影响下次循环
    print('')  # 百位相同的结果显示为一行,百位数字改变的时候换行
print('最终结果为:%s个' % count)

Guess you like

Origin blog.csdn.net/qq_28821897/article/details/129753473