繁体   English   中英

STL 中 next_permutation 的 Python 实现

[英]Python implementation for next_permutation in STL

next_permutation 是一个 C++ 函数,它给出字符串的按字典顺序排列的下一个排列。 可以从这篇非常棒的帖子中获得有关其实现的详细信息。 http://wordaligned.org/articles/next-permutation

  1. 有没有人知道 Python 中的类似实现?
  2. STL迭代器是否有直接的python等价物?

next_permutation是一个C ++函数,按字典顺序给出字符串的下一个排列。 可以从这篇非常棒的文章中获得有关其实现的详细信息。 http://wordaligned.org/articles/next-permutation

  1. 有人知道Python中有类似的实现吗?
  2. 是否有STL迭代器的直接python等效项?

next_permutation是一个C ++函数,按字典顺序给出字符串的下一个排列。 可以从这篇非常棒的文章中获得有关其实现的详细信息。 http://wordaligned.org/articles/next-permutation

  1. 有人知道Python中有类似的实现吗?
  2. 是否有STL迭代器的直接python等效项?

next_permutation是一个C ++函数,按字典顺序给出字符串的下一个排列。 可以从这篇非常棒的文章中获得有关其实现的详细信息。 http://wordaligned.org/articles/next-permutation

  1. 有人知道Python中有类似的实现吗?
  2. 是否有STL迭代器的直接python等效项?

next_permutation是一个C ++函数,按字典顺序给出字符串的下一个排列。 可以从这篇非常棒的文章中获得有关其实现的详细信息。 http://wordaligned.org/articles/next-permutation

  1. 有人知道Python中有类似的实现吗?
  2. 是否有STL迭代器的直接python等效项?

next_permutation是一个C ++函数,按字典顺序给出字符串的下一个排列。 可以从这篇非常棒的文章中获得有关其实现的详细信息。 http://wordaligned.org/articles/next-permutation

  1. 有人知道Python中有类似的实现吗?
  2. 是否有STL迭代器的直接python等效项?

该算法在模块more_itertools作为函数more_itertools.distinct_permutations一部分more_itertools.distinct_permutations

def next_permutation(A):
            # Find the largest index i such that A[i] < A[i + 1]
            for i in range(size - 2, -1, -1):
                if A[i] < A[i + 1]:
                    break
            #  If no such index exists, this permutation is the last one
            else:
                return

            # Find the largest index j greater than j such that A[i] < A[j]
            for j in range(size - 1, i, -1):
                if A[i] < A[j]:
                    break

            # Swap the value of A[i] with that of A[j], then reverse the
            # sequence from A[i + 1] to form the new permutation
            A[i], A[j] = A[j], A[i]
            A[i + 1 :] = A[: i - size : -1]  # A[i + 1:][::-1]

或者,如果保证序列只包含不同的元素,那么next_permutation可以使用模块more_itertools函数来实现:

import more_itertools

# raises IndexError if s is already the last permutation
def next_permutation(s):
   seq = sorted(s)
   n = more_itertools.permutation_index(s, seq)
   return more_itertools.nth_permutation(seq, len(seq), n+1)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM