This week only. Pastebin PRO Accounts Christmas Special! Don't miss out!Want more features on Pastebin? Sign Up, it's FREE!
Guest

meecrob

By: a guest on Oct 16th, 2009  |  syntax: Python  |  size: 1.63 KB  |  views: 128  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. '''Bifid cypher/decypher for strings
  2.         Author: meecrob
  3.         For: programmingpraxis.com
  4.         URL: http://programmingpraxis.com/2009/10/13/bifid-cipher/'''
  5.  
  6. cypher_table = ['ABCDE', 'FGHIK', 'LMNOP', 'QRSTU', 'VWXYZ']
  7.  
  8. def getLetter(row,col):
  9.         return cypher_table[row-1][col-1] # normalize for 0 based access
  10.  
  11. def getRowCol(letter):
  12.         for val in cypher_table:
  13.                 if val.find(letter) != -1:
  14.                         return cypher_table.index(val)+1, val.find(letter)+1 # increment by one to adhere to bifid cypher
  15.         return -1, -1 #return tuple with -1 -1 if unknown
  16.  
  17. def cypher(input_string):
  18.         rows=list()
  19.         columns=list()
  20.         for letter in input_string:
  21.                 row, column = getRowCol(letter)
  22.                 rows.append(row)
  23.                 columns.append(column)
  24.         #print input_string
  25.         #print rows
  26.         #print columns
  27.         combined = (rows+columns)[:]
  28.         final=list()
  29.         for i in range(len(combined)/2):
  30.                 final.append(getLetter(combined[i*2],combined[i*2+1])) #convert pairs into letters
  31.        
  32.         return "".join(final) #return string instead of a list
  33.        
  34. def decypher(input_string):
  35.         rows=list()
  36.         columns=list()
  37.         combined=list()
  38.  
  39.         for letter in input_string:
  40.                 row,col = getRowCol(letter)
  41.                 combined.append(row) #append pairs
  42.                 combined.append(col)
  43.  
  44.         rows = combined[0:(len(combined)/2)] # first half is rows
  45.         columns = combined[(len(combined)/2):len(combined)] #second half is columns
  46.         final=list()
  47.         for i in range(len(rows)):
  48.                 final.append(getLetter(rows[i],columns[i])) # get letters based on rows and columns
  49.         return "".join(final) #return string, not list
  50.  
  51. if __name__ == "__main__":
  52.         toCypString = "PROGRAMMINGPRAXIS"
  53.         cyp= cypher(toCypString)
  54.         print toCypString
  55.         print cyp
  56.         print decypher(cyp)
clone this paste RAW Paste Data