简体   繁体   中英

Next Biggest Number Same Digits

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, ie 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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM