Search code examples
pythonmatrixfillchars

Python: Insert two sets of chars into a matrix


Working with the Playfair cipher. I have two sets of chars: a keyword and the rest of the alphabet without the characters within the keyword. Example (Due to the nature of the Playfair cipher, 'i' is not taken into account to work with 25 characters, good fit for a 5x5 matrx):

    keyword = 'keyword'
    alphabet = 'abcfghjlmnpqstuvxz'

I have an empty 5x5 matrix which I need to fill out, first with the keyboard and then with the rest of the alphabet. With this keyword, the matrix should look like this:

    [k, e, y, w, o]
    [r, d, a, b, c]
    [f, g, h, j, l]
    [m, n, p, q, s]
    [t, u, v, x, z]

This is how I'm trying to insert the keyword characters but I'm stuck from here. when this nested loop is done, the matrix is filled up with 0's:

    #uniquechars is the keyword
    uniqueLen = len(uniqueChars)
    keywordCounter = 0

    for i in range(0, 5):
        for j in range(0, 5):
            while keywordCounter < uniqueLen:
                #print('keywordCounter: ', keywordCounter)
                #print('uniqueLen: ', uniqueLen)
                #print(uniqueChars[keywordCounter])
                matrix[i][j] = uniqueChars[keywordCounter]
                keywordCounter = keywordCounter + 1
                #print(matrix[i][j])

And I don't know how to get the rest of the alphabet in there.

Any ideas?


Solution

  • You can just concatenate the strings and then just iterate it in order. Then use the floor operation // and the modulus operator % to get the correct indices into the matrix.

    >>> keyword = 'keyword'
    >>> alphabet = 'abcfghjlmnpqstuvxz'
    >>>
    >>> # Make an empty matrix -- could also use numpy chararray for this, but
    >>> # this is good enough for this example. 
    >>> matrix = [[None] * 5 for i in range(5)]
    >>>  
    >>> full_string = keyword + alphabet
    >>> 
    >>> for i in range(25):
    ...    matrix[i // 5][i % 5] = full_string[i]
    >>>  
    >>> for row in matrix:
    ...    print(row)
    ['k', 'e', 'y', 'w', 'o']
    ['r', 'd', 'a', 'b', 'c']
    ['f', 'g', 'h', 'j', 'l']
    ['m', 'n', 'p', 'q', 's']
    ['t', 'u', 'v', 'x', 'z']