By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
444,050 Members | 1,020 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 444,050 IT Pros & Developers. It's quick & easy.

List problems in C code ported to Python

P: n/a
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
Jul 18 '05 #1
Share this Question
Share on Google+
20 Replies


P: n/a
Lucas Raab wrote:
Please see both the Python and C code at
http://home.earthlink.net/~lvraab. The two files are ENIGMA.C and engima.py


If you post a small testcase here you are much more likely to get helped.
--
Michael Hoffman
Jul 18 '05 #2

P: n/a
On 2005-01-16, Lucas Raab <py*********@hotmail.com> 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


http://www.catb.org/~esr/faqs/smart-questions.html

--
Grant Edwards grante Yow! Did an Italian CRANE
at OPERATOR just experience
visi.com uninhibited sensations in
a MALIBU HOT TUB?
Jul 18 '05 #3

P: n/a
Grant Edwards wrote:
On 2005-01-16, Lucas Raab <py*********@hotmail.com> 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

http://www.catb.org/~esr/faqs/smart-questions.html


I didn't expect to get bitched out just because I didn't follow "protocol."
Jul 18 '05 #4

P: n/a
"Lucas Raab" <py*********@hotmail.com> wrote in message
news:vr**************@newsread3.news.atl.earthlink .net...
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
Jul 18 '05 #5

P: n/a
"Paul McGuire" <pt***@austin.rr._bogus_.com> wrote:
"A" == 'a' is true in Python, not true in C.


It could be true in C, if the string is stored in very low memory :-)
Jul 18 '05 #6

P: n/a
Paul McGuire wrote:
So "A" == 'a' is true in Python, not true in C.

"A" == 'a' False

I think you meant:
"A" == "A"

True
--
Michael Hoffman
Jul 18 '05 #7

P: n/a
Paul McGuire wrote:
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
Jul 18 '05 #8

P: n/a
Lucas Raab wrote:
Grant Edwards wrote:
http://www.catb.org/~esr/faqs/smart-questions.html


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


I didn't see anyone bitch you out. And you were lucky that one
person was kind enough to go through your web site and make some
suggestions. If you had written a better question I guarantee you would
have had more people answering your question sooner.

Oh yeah, and:

http://www.catb.org/~esr/faqs/smart-...tml#not_losing
--
Michael Hoffman
Jul 18 '05 #9

P: n/a
Michael Hoffman wrote:
Paul McGuire wrote:
So "A" == 'a' is true in Python, not true in C.

I think you meant:
>>> "A" == "A"

True


Er, "A" == 'A'
--
Michael Hoffman
Jul 18 '05 #10

P: n/a
On 2005-01-16, Lucas Raab <py*********@hotmail.com> wrote:
Please see both the Python and C code at
http://home.earthlink.net/~lvraab. The two files are ENIGMA.C
and engima.py


http://www.catb.org/~esr/faqs/smart-questions.html


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.

--
Grant Edwards grante Yow! Hello? Enema
at Bondage? I'm calling
visi.com because I want to be happy,
I guess...
Jul 18 '05 #11

P: n/a
"Michael Hoffman" <ca*******@mh391.invalid> wrote in message
news:cs**********@gemini.csx.cam.ac.uk...
Michael Hoffman wrote:
Paul McGuire wrote:
So "A" == 'a' is true in Python, not true in C.

I think you meant:
>>> "A" == "A"

True


Er, "A" == 'A'
--
Michael Hoffman


Yeah, that's the one I meant... :)

-- Paul
Jul 18 '05 #12

P: n/a
Grant Edwards wrote:
On 2005-01-16, Lucas Raab <py*********@hotmail.com> wrote:

Please see both the Python and C code at
http://home.earthlink.net/~lvraab. The two files are ENIGMA.C
and engima.py

http://www.catb.org/~esr/faqs/smart-questions.html


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.
Jul 18 '05 #13

P: n/a
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/Coo.../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

Jul 18 '05 #14

P: n/a
On 2005-01-17, Lucas Raab <py*********@hotmail.com> wrote:
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.

--
Grant Edwards grante Yow! LOU GRANT froze
at my ASSETS!!
visi.com
Jul 18 '05 #15

P: n/a
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


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[i],[j] = (rotor[order[i-1]],[j]-'A'+26)%26
data[8-i],[data[i],[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[i][j] = ((int)(rotor[order[i-1]][j])-'A' + 26) % 26;
data[8-i][data[i][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.
Jul 18 '05 #16

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

gives

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

Jul 18 '05 #17

P: n/a
On 2005-01-17, Lucas Raab <py*********@hotmail.com> wrote:
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.

--
Grant Edwards grante Yow! My ELBOW is a remote
at FRENCH OUTPOST!!
visi.com
Jul 18 '05 #18

P: n/a
>>> l = []
for i in range(2):
for j in range(2):
l[i][j] = 'x'

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

So you still have to dimension the list before you can use it , eg likel = []
for i in range(2):
l.append([])
for j in range(2):
l[i].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

Jul 18 '05 #19

P: n/a
On 2005-01-17, wi******@hotmail.com <wi******@hotmail.com> wrote:
l = []
for i in range(2):

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

Traceback (most recent call last):
File "<pyshell#7>", line 3, in -toplevel-
l[i][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[i].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.

--
Grant Edwards grante Yow! I always wanted a
at NOSE JOB!!
visi.com
Jul 18 '05 #20

P: n/a
On Mon, 17 Jan 2005 15:28:56 GMT, Lucas Raab <py*********@hotmail.com> wrote:
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
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:

I urge you to explore interactively. And do it line by line
(and even expression by expression when you get mystifying results) until you
are more familiar with the language.

E.g., what do you think the values of j will be here?
j=0
for j in j<26, j+1: print j, ...
True 1

Surprised?
j<26, j+1 (True, 2)

Hm, surprised at the 2 here?
j=0
j<26, j+1 (True, 1)

IOW, your 'for' line was equivalent to iterating through a length-2 tuple
for j in (True, 1): # since if j is 0, j<26 is True, and j+1 is 1
What you probably wanted was j starting with 0 and ending with 25, which you get by
for j in xrange(26): print j, ...
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25

(The comma at the end of the print statement is to get a space before
the next output instead of a newline).
data[4],[j] = (ref_rotor[j] - 'A'+26) % 26 Had you tried an interactive experiment, you would have had some real questions to ask ;-)
j=0
for j in xrange(26): ... data[4],[j] = (ref_rotor[j] - 'A'+26) % 26
...
Traceback (most recent call last):
File "<stdin>", line 2, in ?
NameError: name 'ref_rotor' is not defined

Ok, fix that with something ref_rotor = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' # something legal
j=0
for j in xrange(26): ... data[4],[j] = (ref_rotor[j] - 'A'+26) % 26
...
Traceback (most recent call last):
File "<stdin>", line 2, in ?
TypeError: unsupported operand type(s) for -: 'str' and 'str'

You might have had to ask at this point what that meant, but you could get closer by
trying the expressions and their terms:
(ref_rotor[j] - 'A'+26) % 26 Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: unsupported operand type(s) for -: 'str' and 'str'

Pare it down
(ref_rotor[j] - 'A'+26) Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: unsupported operand type(s) for -: 'str' and 'str'

Check pieces j 0 ref_rotor[j] 'A'

Substitute to make painfully clear
('A' - 'A'+26) Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: unsupported operand type(s) for -: 'str' and 'str' ('A' - 'A') Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: unsupported operand type(s) for -: 'str' and 'str'

What is 'A' ? type('A') <type 'str'>

Hm, characters are strings, not char types that are directly type compatible
with int. It takes a conversion. To get from single-char string to its integer code
and back:
ord('A') 65 chr(65) 'A'

Another experiment:
ord('AB') Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: ord() expected a character, but string of length 2 found
Now you are in a position to use ord, and get a little further:
j=0
for j in xrange(26): ... data[4],[j] = (ord(ref_rotor[j]) - ord('A')+26) % 26
...
Traceback (most recent call last):
File "<stdin>", line 2, in ?
TypeError: unpack non-sequence

Was the right hand side a problem? j 0 (ord(ref_rotor[j]) - ord('A')+26) % 26 0

Apparently not, so what it was trying to do was
data[4],[j] = 0 Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: unpack non-sequence

What was it trying to unpack? And why?
Well, you might have known if you had been through the tutorial, but at least
you would have had a specific question about a specific error at this point.

Note: a, b = 0 Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: unpack non-sequence

I.e., when you have commas (or even one) on the left hand side of an assignment,
that is asking python to unpack a sequence on the right hand side and assign to
corresponding items on the left. So e.g.,
a, b = 0, 1 will unpack the tuple formed by 0, 1 a 0 b 1
You can unpack any sequence of the same length, and strings happen to be sequences:
a,b = 'XY'
a 'X' b 'Y'

Ok, enough of that. The comma was obviously a problem so, try it without:

data[4][j] = 0

Traceback (most recent call last):
File "<stdin>", line 1, in ?
NameError: name 'data' is not defined

I could go on, but IMO if you expect help, you should do your part, and at least
post code that you have tried and which compiles or runs up to the point where
it shows an error that you need help with.

And show a verbatim copy/paste from your interactive session, not uncompilable
and obviously totally untested stuff.

for i in i<4, i+1:
step[i-1] = step_data[order[i-1]]
for j in j<26, j+1:
data[i],[j] = (rotor[order[i-1]],[j]-'A'+26)%26
data[8-i],[data[i],[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[i][j] = ((int)(rotor[order[i-1]][j])-'A' + 26) % 26;
data[8-i][data[i][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.


You are obviously not yet familiar with python, but a few hours with the
introduction and tutorials should help a lot. Then post something that
compiles. Or a snippet that does something you don't understand.

This is about all I have patience for this time. I really have other stuff to do.

Regards,
Bengt Richter
Jul 18 '05 #21

This discussion thread is closed

Replies have been disabled for this discussion.