I am building a cypher program which uses a matrix of numbers and letters. A message is encoded according to the row and column each letter of the message is found in the matrix.

I am trying to find a nice way of iterating over the 2D matrix (6*6).

 for char in range (0, len(message), 1):
  for i in range(0, len(rows), 1):
    for y in range(0, len(cols), 1):
      if matrix[i][y] == message[char]:
         cyphermessage.append(" ")

But this method uses a 3-tier for loop which makes it \$\mathcal{O}((N)*3)\$, plus the the cypher append messages are quite ugly.


Don't search – find. Specifically, don't iterate through all matrix entries for each character. Instead, build a dictionary that maps the characters in the matrix to a pair of indices.

Also, don't loop over indices (in message) unless you have to. Now we have:

position_lookup = dict()
for x in range(len(matrix)):
  for y in range(len(matrix[x])):
    position_lookup[matrix[x][y]] = (x, y)

for char in message:
  if char in position_lookup:
    x, y = position_lookup[char]
    cyphermessage.extend([x, y, " "])

Technically, this behaves different from the code you wrote: consider what happens when one character occurs multiple times in the matrix – I only use the last occurrence, while you append all possibilities.

| improve this answer | |
  • \$\begingroup\$ let me read about dictionaries, an ill get back to you with relevant points. \$\endgroup\$ – Babbleshack Dec 15 '13 at 15:02
  • \$\begingroup\$ could i add a third field to the dictionary to use as a key; for instance, i am using the row/collum lable as the cypher, rather than haveing 01 i would have AB \$\endgroup\$ – Babbleshack Dec 15 '13 at 15:30
  • \$\begingroup\$ am sorry i misunderstood the code, the problem is i need to change position_lookup[matrix[x][y]] = (x, y) so that the values store will be A,A for position 0,0. so instaed of using a number as the key i would store a char letter (A-F) \$\endgroup\$ – Babbleshack Dec 15 '13 at 15:35
  • \$\begingroup\$ @Babbleshack I don't quite understand what you are trying to do – I just showed a way to improve your code. If you need to change what your code does, stackoverflow might be of more help. Anyway, what would be wrong with translating the indices along the lines of letters = "ABCDEFG"; letter = letters[i]? \$\endgroup\$ – amon Dec 15 '13 at 15:54
  • \$\begingroup\$ haha excellent idea! thanks for that, and i realize that i asked a seperate questions, sorry about that! \$\endgroup\$ – Babbleshack Dec 15 '13 at 16:16

Not the answer you're looking for? Browse other questions tagged or ask your own question.