Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- '''Bifid cypher/decypher for strings
- Author: meecrob
- For: programmingpraxis.com
- URL: http://programmingpraxis.com/2009/10/13/bifid-cipher/'''
- cypher_table = ['ABCDE', 'FGHIK', 'LMNOP', 'QRSTU', 'VWXYZ']
- def getLetter(row,col):
- return cypher_table[row-1][col-1] # normalize for 0 based access
- def getRowCol(letter):
- for val in cypher_table:
- if val.find(letter) != -1:
- return cypher_table.index(val)+1, val.find(letter)+1 # increment by one to adhere to bifid cypher
- return -1, -1 #return tuple with -1 -1 if unknown
- def cypher(input_string):
- rows=list()
- columns=list()
- for letter in input_string:
- row, column = getRowCol(letter)
- rows.append(row)
- columns.append(column)
- #print input_string
- #print rows
- #print columns
- combined = (rows+columns)[:]
- final=list()
- for i in range(len(combined)/2):
- final.append(getLetter(combined[i*2],combined[i*2+1])) #convert pairs into letters
- return "".join(final) #return string instead of a list
- def decypher(input_string):
- rows=list()
- columns=list()
- combined=list()
- for letter in input_string:
- row,col = getRowCol(letter)
- combined.append(row) #append pairs
- combined.append(col)
- rows = combined[0:(len(combined)/2)] # first half is rows
- columns = combined[(len(combined)/2):len(combined)] #second half is columns
- final=list()
- for i in range(len(rows)):
- final.append(getLetter(rows[i],columns[i])) # get letters based on rows and columns
- return "".join(final) #return string, not list
- if __name__ == "__main__":
- toCypString = "PROGRAMMINGPRAXIS"
- cyp= cypher(toCypString)
- print toCypString
- print cyp
- print decypher(cyp)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement