0

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?

kaozbender
  • 95
  • 3
  • 8

1 Answers1

1

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']
Andrew Carter
  • 371
  • 1
  • 4
  • Made everything simpler, thanks. However, then using "for i in range(25): ... matrix[i // 5][i % 5] = full_string[i]" I get this error: IndexError: list index out of range. any ideas? – kaozbender Mar 04 '15 at 05:10
  • 1
    You would have to post your exact code. I try to post fully run-able examples, and this example is a fully working docstring (you can test it in doctest, if you like). So you must not have defined your `matrix` variable in the same way. – Andrew Carter Mar 04 '15 at 05:15
  • Mistake on my part. Worked just fine. Thank you very much. – kaozbender Mar 04 '15 at 05:38