简体   繁体   中英

How to prevent combination of more than 3 characters in a loop of all permutations of a string

def toString(List): 
    return ''.join(List) 

# The main function that recursively prints all repeated permutations of the given string.

def allLexicographicRecur (string, data, last, index): 
    length = len(string) 

    for i in xrange(length): 
        data[index] = string[i] 
        if index==last: 
            print toString(data) 
        else: 
            allLexicographicRecur(string, data, last, index+1) 
 
def allLexicographic(string): 
    length = len(string) 
    data = [""] * (length+1) 
    string = sorted(string) 
    allLexicographicRecur(string, data, length-1, 0) 

string = "abcde"
allLexicographic(string) 

output

aaaaa
aaaab
aaaac
aaaad
aaaae
aaaba
...
eeede
eeeea
eeeeb
eeeec
eeeed
eeeee

I want to make my loop prevent a repetition of a character more than two times in same string

FOR EXAMPLE

**SKIPPED STRINGS**
aaaaa will be skipped
aaaab will be skipped
aaaac will be skipped
...
aaaba will be skipped
abeee will be skipped

**NOT SKIPPED STRINGS**
abaab will not be skipped
abada will not be skipped

etc

The code should skip the above strings and they should not be printed out

The main idea is to reduce computational time and increase output speed significantly

A solution where the strings are generated then filtered is highly discouraged because this will double the work instaed of reducing it

on a kind note please vote my question up if its a good one thanks

I see no better way than to store the last generated letter, and count the number of times it has been generated in sequence.
If you generate a different one, overwrite and reset the counter.
If you are about to generate the third one, skip that letter and take the next one.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM