K
K
Kit Scribe2020-10-21 01:18:35
Python
Kit Scribe, 2020-10-21 01:18:35

How can the algorithm be improved so that it runs faster?

There is an algorithm for finding the next larger number in permutations of this number. But he's not fast enough.
How can it be improved?

The code
import itertools

def next_bigger(n):
    nlst = list(str(n))

    for i in range(len(nlst) - 1, -1, -1):
        tempLst1 = nlst[:i]
        tempLst2 = nlst[i:]

        vs = list(itertools.permutations(tempLst2, len(tempLst2)))

        temp = [int("".join(tempLst1 + list(x))) for x in vs if int("".join(tempLst1 + list(x))) > n]
        if len(temp) >= 1:
            return min(temp)

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question