List problems in C code ported to Python

L

Lucas Raab

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
 
P

Paul McGuire

Lucas Raab said:
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

I didn't actually run your script, but you have some fundamental things to
fix first. Here are some corrections that will get you closer:

- Single-character strings are still strings as far as Python is concerned.
Unlike C's distinction of single quotes for single characters (which allow
you to do integer arithmetic) and double quotes for string literals (which
don't support integer arithmetic), Python uses either quoting style for
strings. So "A" == 'a' is true in Python, not true in C. To do single-char
arithmetic, you'll need the ord() and asc() functions, so that instead of
c-'A'
you'll need
ord(c)-ord('A')
(and another little tip - since the ord('A') is likely to be invariant, and
used *heavily* in a function such as an Enigma simulator, you're best off
evaluating it once and stuffing it into a global, with an unimaginitive name
like ord_A = ord('A')

-Line 42: You are testing c == string.alpha_letters, when I think you
*really* want to test c in string.alpha_letters.

- encipher_file - the C version of this actually reads the file and calls
encipher() with each character in it. Your Python version just calls
encipher() with the complete file contents, which is certain to fail.
(another tip - avoid variable names like 'file', 'string', 'list', 'dict',
etc. as these collide with global typenames - also, your variable naming is
pretty poor, using "file" to represent the filename, and "filename" to
represent the file contents - err???)

- usage() - print("blahblah \n") - the trailing \n is unnecessary unless you
want to double-space your text

Although you say you are "done porting the C code", you really have quite a
bit left to do yet. You should really try to port this code a step at a
time - open a file, read its contents, iterate through the contents, call a
method, etc. "Big-bang" porting like this is terribly inefficient!

-- Paul
 
I

Irmen de Jong

Paul said:
So "A" == 'a' is true in Python, not true in C.

It's not true in Python either.
You probably meant to say: "a" == 'a'
(lowercase a)

--Irmen
 
G

Grant Edwards

I didn't expect to get bitched out just because I didn't
follow "protocol."

You didn't get "bitched out". You did get some very sound
advice. You want help solving a problem, and there are ways you
can greatly increase the chances that you'll get help with your
problem. After being told the best ways to get help, you
whined about it rather than following it.

Nobody owes you anything.

Remember that.

[You're darned lucky somebody did take the time to go to your
web site and proof your code for you after your posting said in
effect "I'm too lazy to compose and post a precise question, so
go look at my program and fix it for me."]

Now, go back and read the smart questions reference.
 
L

Lucas Raab

Grant said:
I didn't expect to get bitched out just because I didn't
follow "protocol."


You didn't get "bitched out". You did get some very sound
advice. You want help solving a problem, and there are ways you
can greatly increase the chances that you'll get help with your
problem. After being told the best ways to get help, you
whined about it rather than following it.

Nobody owes you anything.

Remember that.

[You're darned lucky somebody did take the time to go to your
web site and proof your code for you after your posting said in
effect "I'm too lazy to compose and post a precise question, so
go look at my program and fix it for me."]

Now, go back and read the smart questions reference.

Sorry about that. I had a bad day. First there was the migraine and then
the fight with my significant other, so yesterday was not a good day. I
apologize for what I said.
 
W

wittempj

Lucas said:
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 - 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
 
G

Grant Edwards

Sorry about that. I had a bad day. First there was the
migraine and then the fight with my significant other, so
yesterday was not a good day. I apologize for what I said.

No worries. As somebody else said, the best way to get help
solving problems is to post as small an example as possible
that exhibits the problem behavior. This may take a bit of
effort, since problems sometimes go away when you try to
reproduce them in a small example (less than 50 lines or so).
If you can post a small example that doesn't do what you want
it to, I gaurantee that somebody will explain why it doesn't do
what you want and how to fix it.
 
L

Lucas Raab

Lucas said:
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

OK, here's the Python code and the corresponding C code:

def init_mach():
import string
#setup rotor data
i=1
j=0
for j in j<26, j+1:
data[4],[j] = (ref_rotor[j] - 'A'+26) % 26

for i in i<4, i+1:
step[i-1] = step_data[order[i-1]]
for j in j<26, j+1:
data,[j] = (rotor[order[i-1]],[j]-'A'+26)%26
data[8-i],[data,[j]] = j


void
init_mach( void )
{
int i, j;
int ds;
int u, v;

/* setup rotor data */
for (j=0;j<26;j++)
data[4][j] = ((int)ref_rotor[j]-'A'+26)%26;

for (i=1;i<4;i++)
{
step[i-1] = step_data[order[i-1]];
for (j=0;j<26;j++)
{
data[j] = ((int)(rotor[order[i-1]][j])-'A' + 26) % 26;
data[8-i][data[j]] = j;
}
}

Now, do I need to start boning up on lists and how to use them or am I
missing the bigger picture?? Again, for the complete code see
http://home.earthlink.net/~lvraab. I'm not asking you to do it for me,
just some pointers on going about this.
 
W

wittempj

l = []
for i in range(2):
for j in range(2):
l,[j] = 0
print l

gives

Traceback (most recent call last):
File "C:\TEMP\test.py", line 75, in -toplevel-
l,[j] = 0
TypeError: unpack non-sequence
That's why your current code needs a matrix class.
 
G

Grant Edwards

data[4][j] = ((int)ref_rotor[j]-'A'+26)%26;

data[4],[j] = (ref_rotor[j] - 'A'+26) % 26
^
The comma shouldn't be there.

C: data[4][j]
Python: data[4][j]
Now, do I need to start boning up on lists and how to use them

Sort of. I think you mostly just need to sit down and
proofread your code.

I would also advise building your Python app in smaller steps.
Translate one function, and test it to make sure it works. Then
translate the next function and test it to make sure it works.
Then the next function, etc.
 
W

wittempj

l = []for j in range(2):
l[j] = 'x'



Traceback (most recent call last):
File "<pyshell#7>", line 3, in -toplevel-
l[j] = 'x'
IndexError: list index out of range

So you still have to dimension the list before you can use it , eg like
l = []
for i in range(2):
l.append([])
for j in range(2):
l.append(j)


then you do not get the indexerror, but I feel a class is what you need
here to make life easier and the program more readable
 
G

Grant Edwards

l = []
for i in range(2):
for j in range(2):
l[j] = 'x'



Traceback (most recent call last):
File "<pyshell#7>", line 3, in -toplevel-
l[j] = 'x'
IndexError: list index out of range

So you still have to dimension the list before you can use it , eg like
l = []
for i in range(2):
l.append([])
for j in range(2):
l.append(j)


then you do not get the indexerror, but I feel a class is what you need
here to make life easier and the program more readable


I'd probably numeric python (which I beleive is depricated, but
it's what I have installed) or numarray. I think either would
make it a lot easier. Using lists of lists when what you want
is a matrix can be made to work, but there are a lot of
non-obvious traps to fall into.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,744
Messages
2,569,483
Members
44,902
Latest member
Elena68X5

Latest Threads

Top