首页
学习
活动
专区
圈层
工具
发布
社区首页 >专栏 >python 下一个排列 多种解法

python 下一个排列 多种解法

作者头像
编程小白狼
发布2024-12-31 08:18:00
发布2024-12-31 08:18:00
1890
举报
文章被收录于专栏:编程小白狼编程小白狼

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

示例代码如下:

代码语言:javascript
复制
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)

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

示例代码如下:

代码语言:javascript
复制
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)
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2024-01-13,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档