You have to create a function that takes a positive integer number and returns the next bigger number formed by the same digits: If no bigger number can be composed using those digits, return -1:
examples:
next_bigger(12)==21
next_bigger(513)==531
next_bigger(2017)==2071
next_bigger(9)==-1
next_bigger(111)==-1
next_bigger(531)==-1
Slow but elegant solution:
import itertools
def next_bigger(n):
s = sorted(list(set([''.join(x) for x in itertools.permutations(str(n))])))
return int(s[s.index(str(n))+1]) if len(s) >= s.index(str(n)) +1 else -1
Hi @woohgit, the above implementation is as your say very elegant yet very slow. But nonetheless its a good and Pythonic way of achieving the solution. But it is has errors Have you run the script? The last three assertions you're making namely for digits 9, 111, 531 gives an IndexError. So update you solution to return -1 when such an Exception is found. In all the above mentioned cases the reason for the IndexError can easily be deduced. The Exception is as expected because you're trying to access the element
s[s.index(str(n))+1
Meaning for those specific cases the item trying to be accessed falls outside because there is not higher item in the list.