Python algorithm design - the next set of permutations

Python algorithm design source code: https://github.com/MakerChen66/Python3Algorithm

Copyright statement: Originality is not easy, this article prohibits plagiarism, reprinting, infringement must be investigated!

1. The next group arrangement

Given a fully ordered set, we need to find the next set of permutations of the current structure, such as: HIJT->HITJ->HJIT->HJTI...

Although almost every library provides similar functions, if you want to improve For algorithm speed, you can take a look at this.

The algorithm itself is very simple:

  • Starting from the end of the sequence, find the longest descending subsequence (eg: 46 975 ) and represent the item before it as a pivot (eg: 4 6 975 )
  • Exchange this pivot point with the next smallest term in the found descending longest subsequence (eg: 4 7 9 6 5)
  • Turn the descending subsequence (eg: 47569)

Python algorithm implementation:

def permute(value):
    values = list(value)
    n = len(values)

    # i: 找到递减序列前的那一个支点
    for i in reversed(range(n - 1)):
        if values[i] < values[i + 1]:
            break
    else:
        # 否则逆转列表里的元素
        values[:] = reversed(values[:])
        return values

    # j: 要和i支点交换值的递减序列的次小项
    for j in reversed(range(i, n)):
        if values[i] < values[j]:
            # i支点和递减序列的次小项交换值,并且把交换后的递减序列逆转,也就是把i支点后的元素逆转
            values[i], values[j] = values[j], values[i]
            values[i + 1:] = reversed(values[i + 1:])
            break

    print(values)

permute('HIJT')

output result:
insert image description here

2. Source code download

Python algorithm design source code download:

3. Author Info

Author: Xiaohong's Fishing Daily, Goal: Make programming more interesting!

Original WeChat public account: " Xiaohong Xingkong Technology ", focusing on algorithms, crawlers, websites, game development, data analysis, natural language processing, AI, etc., looking forward to your attention, let us grow and code together!

Copyright Note: This article prohibits plagiarism and reprinting, and infringement must be investigated!

Guess you like

Origin blog.csdn.net/qq_44000141/article/details/121866025