小编ZeO*_*One的帖子

使排列函数更有效

我正在解决一个代码战争卡塔问题,但正在努力弄清楚如何使我的函数更高效,因为我一直被涉及大量数字的测试用例所困扰。

卡塔的说明如下:

创建一个函数,它接受一个正整数并返回可以通过重新排列其数字形成的下一个更大的数字。例如:

12 ==> 21
513 ==> 531
2017 ==> 2071
nextBigger(num: 12)   // returns 21
nextBigger(num: 513)  // returns 531
nextBigger(num: 2017) // returns 2071
Run Code Online (Sandbox Code Playgroud)

如果无法重新排列数字以形成更大的数字,则返回 -1(或在 Swift 中为 nil):

9 ==> -1
111 ==> -1
531 ==> -1
Run Code Online (Sandbox Code Playgroud)

(我很确定)我的代码没有错误,唯一的问题是它的效率:

from itertools import permutations

def next_bigger(n):
    possible_nums = [int(''.join(p)) for p in permutations(str(n))]
    possible_nums = list(dict.fromkeys(possible_nums))
    print(possible_nums)
    if possible_nums.index(n)+1 == len(possible_nums):
        return -1
    else:
        return possible_nums[possible_nums.index(n)+1]
Run Code Online (Sandbox Code Playgroud)

我不知道permutation()函数是什么导致了问题,list(dict.fromkeys(possible_nums))但我似乎无法找到一种更有效的方法来查找数字的每个排列n。非常感谢我是否应该重构整个函数或只是替换一些代码以使其更高效!

python algorithm performance permutation python-3.x

3
推荐指数
1
解决办法
183
查看次数

标签 统计

algorithm ×1

performance ×1

permutation ×1

python ×1

python-3.x ×1