0
点赞
收藏
分享

微信扫一扫

python 下一个排列 多种解法

方法一:使用内置函数 Python 提供了一个内置函数 next_permutation,可以直接用来求解下一个排列。你可以通过导入 itertools 模块来使用该函数。

示例代码如下:

import itertools

nums = [1, 2, 3]
perms = list(itertools.permutations(nums))
next_perm = perms[perms.index(tuple(nums))+1] if tuple(nums) in perms else []
print(next_perm)

方法二:自定义函数 你也可以自己编写一个函数来实现下一个排列的求解。

示例代码如下:

def next_permutation(nums):
    # 找到第一个降序的位置
    i = len(nums) - 2
    while i >= 0 and nums[i] >= nums[i + 1]:
        i -= 1

    if i >= 0:
        # 找到第一个比 nums[i] 大的数的位置
        j = len(nums) - 1
        while nums[j] <= nums[i]:
            j -= 1
    
        # 交换位置
        nums[i], nums[j] = nums[j], nums[i]

    # 反转后面的数字
    left, right = i + 1, len(nums) - 1
    while left < right:
        nums[left], nums[right] = nums[right], nums[left]
        left += 1
        right -= 1

    return nums

nums = [1, 2, 3]
next_perm = next_permutation(nums)
print(next_perm)

举报

相关推荐

0 条评论