List problems in C code ported to Python

wittempj at hotmail.com wittempj at hotmail.com
Mon Jan 17 08:41:29 EST 2005


Lucas Raab wrote:
> I'm done porting the C code, but now when running the script I
> continually run into problems with lists. I tried appending and
> extending the lists, but with no avail. Any help is much appreciated
> Please see both the Python and C code at
> http://home.earthlink.net/~lvraab. The two files are ENIGMA.C and
engima.py
>
> TIA

You need something like a matrix too for this, if we combine this with
the
already posted idea of caching of 'ord' results you could go this way:

class matrix(object):
"""based on
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/189971
"""
def __init__(self, *args):
from types import IntType, StringType

self.__data = []

if len(args) == 2 and type(args[0]) == IntType and type(args[1]
== IntType):
#args[0] = #rows, args[1] = #columns
for r in range(args[0]):
self.__data.append([])
for j in range(args[1]):
self.__data[r].append(0)
else:
for arg in args:
if type(arg) == StringType:
self.__data.append(map(ord, list(arg)))

def __repr__(self):
ret = ''
for r in self.__data:
ret = '%s\n%s' % (ret, r)

return ret

def __getitem__(self, (row, col)):
return self.__data[row][col]

def __setitem__(self, (row, col), value):
self.__data[row][col] = value



#setup rotor data
A = ord('A')
ref_rotor = map(ord, "YRUHQSLDPXNGOKMIEBFZCWVJAT")
print ref_rotor

data = matrix(8, 26)
for i in range(26):
data[(4, i)] = (ref_rotor[i] - A + 26) % 26
print data

step_data = (16,  4, 21,  9, 25) #steps at: q, e, v, j, z
order = range(3)
rotor = matrix("EKMFLGDQVZNTOWYHXUSPAIBRCJ",
"AJDKSIRUXBLHWTMCQGZNPYFVOE", \
"BDFHJLCPRTXVZNYEIWGAKMUSQO",
"ESOVPZJAYQUIRHXLNFTGKDCMWB", \
"VZBRGITYUPSDNHLXAWMJQOFECK")
step = range(3)
for i in range(1, 4):
step[i - 1] = step_data[order[i-1]]
for j in range(26):
data[(i, j)] = (rotor[(order[i-1], j)] - A + 26) % 26
print data




More information about the Python-list mailing list