-6

I don't see anything wrong with my code but I can't seem to return -1 when the input cannot produce a next bigger number, i.e. input of 531 which is descending.

import itertools as it
def next_bigger(n):
    if sorted("531", reverse = True) == list("531"):
        return -1
    s = tuple(str(n))
    for x in it.dropwhile(lambda x: x <= s, it.permutations(sorted(s))):
        return int(''.join(x))
    return s

Can someone please help?

Mr. Jibz
  • 511
  • 2
  • 7
  • 21

1 Answers1

2

You can simply use an if statement at the beginning of your function to test whether the number is already in reverse sorted order. If it is sorted return -1 straight away:

>>> sorted("531", reverse = True) == list("531")
True
Chris_Rands
  • 38,994
  • 14
  • 83
  • 119