Python3 – Next bigger number with the same digits

Codewars

Source: codewars
You have to create a function that takes a positive integer number and returns the next bigger number formed by the same digits:

next_bigger(12)==21
next_bigger(513)==531
next_bigger(2017)==2071

If no bigger number can be composed using those digits, return -1:

next_bigger(9)==-1
next_bigger(111)==-1
next_bigger(531)==-1

Testing cases

Test.assert_equals(next_bigger(12),21)
Test.assert_equals(next_bigger(513),531)
Test.assert_equals(next_bigger(2017),2071)
Test.assert_equals(next_bigger(414),441)
Test.assert_equals(next_bigger(144),414)

Martin’s Comment

Firstly when I saw this exercise first came to my mind python library for permutations which I used before. From that point it is very easy to solve, you just sort all permutations and cycle through sorted numbers and in case you find a first bigger number you return it.

Martin’s Solution

import itertools
def next_bigger(n):
    for num in sorted([int(''.join(map(str,x))) for x in list(set(itertools.permutations([int(x) for x in str(n)])))]):
        if num>n:
            return num
    return -1