Problem: Write a function that takes a positive integer and returns the next smaller positive integer containing the same digits.
My solution:
def next_smaller(n):
import itertools
x = list(str(n)) #list of digits
#permutates and joins digits
x = [int(''.join(i)) for i in list(itertools.permutations(x))]
x.sort() #sorts numerically
#picks number previous to original in list
r = [x[i-1] for i in range(0,len(x)) if x[i] == n][0]
if r > n: return -1 #returns -1 if no solution
else: return r #returns solution
My code works, however it is terribly inefficient with very large numbers. Any way to make this code more efficient and cut down the execution time?