Hi everyone... Can someone help me?
OUTPUT :
aadt
aatd
adat
adta
atad
atda
daat
data
dtaa
taad
tada
tdaa
CAN OUTPUT TO :
data
data
daat
dtaa
dtaa
daat
data
adta
adat
atda
atad
aadt
aatd
tdaa
tdaa
tada
taad
tada
taad
adat
adta
aadt
aatd
atda
atad
Code:
def lexico_permute_string(s):
''' Generate all permutations in lexicographic order of string `s`
This algorithm, due to Narayana Pandita, is from
https://en.wikipedia.org/wiki/Permutation#Generation_in_lexicographic_order
To produce the next permutation in lexicographic order of sequence `a`
1. Find the largest index j such that a[j] < a[j + 1]. If no such index exists,
the permutation is the last permutation.
2. Find the largest index k greater than j such that a[j] < a[k].
3. Swap the value of a[j] with that of a[k].
4. Reverse the sequence from a[j + 1] up to and including the final element a[n].
'''
a = sorted(s)
n = len(a) - 1
while True:
yield ''.join(a)
#1. Find the largest index j such that a[j] < a[j + 1]
for j in range(n-1, -1, -1):
if a[j] < a[j + 1]:
break
else:
return
#2. Find the largest index k greater than j such that a[j] < a[k]
v = a[j]
for k in range(n, j, -1):
if v < a[k]:
break
#3. Swap the value of a[j] with that of a[k].
a[j], a[k] = a[k], a[j]
#4. Reverse the tail of the sequence
a[j+1:] = a[j+1:][::-1]
for s in lexico_permute_string('data):
aadt
aatd
adat
adta
atad
atda
daat
data
dtaa
taad
tada
tdaa
CAN OUTPUT TO :
data
data
daat
dtaa
dtaa
daat
data
adta
adat
atda
atad
aadt
aatd
tdaa
tdaa
tada
taad
tada
taad
adat
adta
aadt
aatd
atda
atad
Comment