Skip to content

Instantly share code, notes, and snippets.

@woohgit
Last active October 17, 2016 19:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save woohgit/70c6937eac22245e4fb4 to your computer and use it in GitHub Desktop.
Save woohgit/70c6937eac22245e4fb4 to your computer and use it in GitHub Desktop.
Next Big Number

Next Bigger Kata

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
@prlombaard
Copy link

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment