Answer the question
In order to leave comments, you need to log in
Where is the error in the permutation algorithm?
You need to write a function that will return the nearest larger number to the number passed to it by performing permutations.
My code doesn't pass all tests. Where did I go wrong with the algorithm? And how can this be fixed?
def next_bigger(n):
origin = n
n = list(str(n))
for i in range(len(n), 0, -1):
n2 = n[::]
n2[i - 2] = n[i - 1]
n2[i - 1] = n[i - 2]
if int("".join(n2)) > origin:
return int("".join(n2))
return -1
if __name__ == "__main__":
print(next_bigger(12)) # -> 21
print(next_bigger(144)) # -> 414
print(next_bigger(1234567890)) # -> 1234567980! должно быть 1234567908
Answer the question
In order to leave comments, you need to log in
The algorithm should be like this: from the end we look for the first character, such that a[i] < a[i+1], so we determine the smallest bit that will make the number greater than the previous one. Then we need to minimize the "tail" to get the number closest to the original (the smaller the tail, the closer it is to the original). To do this, we sort the tail in ascending order and rearrange our number of the smallest digit with the first number from the tail that is greater than it.
In the example with 1234567890.
1. We are looking for the digit of the smallest digit when a[i] < a[i+1]. It's 8, the tail of [9, 0].
2. Sort the tail [0, 9] and go through it looking for the first digit greater than our 8. This is 9.
3. Swap them and return the result
1234567 8 0 9 => 1234567908
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question