Python programming classic case [examination questions] permutation and combination

This article explores classic cases of Python programming with you, allowing you to learn Python immersively. You can think about the topic first, and then compare it with the problem-solving methods in this article. If you have different opinions, welcome to discuss with me in the official account.

1. Classic case [examination question]

  
question:

1到ipt_num(3)能组成多少个互不相同且不重复的三位数字数组?

enter:

3

output:

13 能组成 6 种互不相同且不重复的三位数
[[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]]

  
  

2. Classic case problem-solving method

  
The solution to the problem in the above case is as follows:
  
Step1: Use three layers of for loops to list all possible numbers between 1 and ipt_num.
  
step2: If the three numbers are different from each other, add them to the result list.
  
The specific code is as follows:

def ord_pl(ipt_num):
    num = ipt_num + 1
    all_num = list()
    for i in range(1, num):
        for j in range(1, num):
            for k in range(1, num):
                if i!=j and i!=k and j!=k:
                    all_num.append([i, j, k])
    print(1, '到', ipt_num, '能组成', len(all_num), '种互不相同且不重复的三位数')
    return all_num
ord_pl(4) 

for i in range(1, num): Generate an arithmetic progression from 1 to ipt_num with a step size of 1.
  
i!=j and i!=k and j!=k: Determine whether i, j, and k are different from each other, and return True if they are different, otherwise return False.
  
got the answer:

14 能组成 24 种互不相同且不重复的三位数
[[1, 2, 3],
 [1, 2, 4],
 [1, 3, 2],
 [1, 3, 4],
 [1, 4, 2],
 [1, 4, 3],
 [2, 1, 3],
 [2, 1, 4],
 [2, 3, 1],
 [2, 3, 4],
 [2, 4, 1],
 [2, 4, 3],
 [3, 1, 2],
 [3, 1, 4],
 [3, 2, 1],
 [3, 2, 4],
 [3, 4, 1],
 [3, 4, 2],
 [4, 1, 2],
 [4, 1, 3],
 [4, 2, 1],
 [4, 2, 3],
 [4, 3, 1],
 [4, 3, 2]]

You can manually verify that the result is correct. The advantage of this method is that the logic is simple and clearer to understand. So far, the classic case of programming in Python [examination questions] permutation and combination has been explained.
  
If you want to know more about functions in Python, you can read related articles on the "Learning Python" module in the official account.
  
You may be interested in:
Draw Pikachu with Python Draw a
word cloud map
with Python Draw 520 eternal heartbeats with
Python With sound and text) Use the py2neo library in Python to operate neo4j and build a relationship map Python romantic confession source code collection (love, rose, photo wall, confession under the stars)



Guess you like

Origin blog.csdn.net/qq_32532663/article/details/127950186