I need to input a string,and returns its next lexicographically bigger string.For example, the next string of 'anmdfg' is 'anmdgf'.However,the length of the input could be very large,it may include 100 characters or more,and there will be some repeated characters in it.So I decide to use itertools.permutations without making it into a list for avoiding the memory over-consumption.
#!/usr/bin/env python3
from itertools import permutations
a = list(input())
tuple_a = tuple(a)
b = permutations(a,len(a))
p = next(b)
result = ''
try:
while 1:
p = next(b)
if p > tuple_a:
result = ''.join(p)
print(result)
break
except:
if result == '':
print('No answer.')
else:
if result == '':
print('No answer.')
The b in my sample isn't sorted.It seems that I have to generate the list first.I tried and it consumed my memory so fast that I had no time to terminate the process. Is there any way for me to sort the result of permutation without making a list?