Generate list of all possible permutations of a string

后端 未结 30 2830
故里飘歌
故里飘歌 2020-11-22 15:10

How would I go about generating a list of all possible permutations of a string between x and y characters in length, containing a variable list of characters.

Any l

30条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-11-22 15:26

    This code in python, when called with allowed_characters set to [0,1] and 4 character max, would generate 2^4 results:

    ['0000', '0001', '0010', '0011', '0100', '0101', '0110', '0111', '1000', '1001', '1010', '1011', '1100', '1101', '1110', '1111']

    def generate_permutations(chars = 4) :
    
    #modify if in need!
        allowed_chars = [
            '0',
            '1',
        ]
    
        status = []
        for tmp in range(chars) :
            status.append(0)
    
        last_char = len(allowed_chars)
    
        rows = []
        for x in xrange(last_char ** chars) :
            rows.append("")
            for y in range(chars - 1 , -1, -1) :
                key = status[y]
                rows[x] = allowed_chars[key] + rows[x]
    
            for pos in range(chars - 1, -1, -1) :
                if(status[pos] == last_char - 1) :
                    status[pos] = 0
                else :
                    status[pos] += 1
                    break;
    
        return rows
    
    import sys
    
    
    print generate_permutations()
    

    Hope this is of use to you. Works with any character, not only numbers

提交回复
热议问题