473,463 Members | 1,494 Online
Bytes | Software Development & Data Engineering Community
Create Post

Home Posts Topics Members FAQ

List problems in C code ported to Python

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
20 2180
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
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
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
"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
"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
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
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
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
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
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
"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
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
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
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
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
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
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
>>> 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
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
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 thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

5
by: Dave Brueck | last post by:
Is anybody else having problems sending email to python-list@python.org? About 48 hours ago or so my posts stopped making it to the list (I usually post via the mailing list rather than to the...
3
by: Brad Clements | last post by:
I have not seen any new posts in gmane.comp.python.general since 6/18/2004. However when I post to gmane, that post seems to make it out to the python list. Does anyone know if its a gmane...
0
by: Armin Steinhoff | last post by:
Hi all, I ported ctypes 0.9.2 to QNX6.3 ... 99.9 % is working but only the unittest test_functions.py makes some problem. Here is the code: p = pointer(c_int(99)) result = f(p)...
0
by: Brian van den Broek | last post by:
Hi all, There have been a few posts over the last month or so expressing a bit of exasperation with the "rising tide of newbie's". (Or, more accurately, the rising tide of questions from...
41
by: Xah Lee | last post by:
here's another interesting algorithmic exercise, again from part of a larger program in the previous series. Here's the original Perl documentation: =pod merge($pairings) takes a list of...
39
by: n00m | last post by:
Given a list of N arbitrarily permutated integers from set {1..N}. Need to find the ordering numbers of each integer in the LONGEST increasing sequence to which this number belongs. Sample: ...
7
by: Brian | last post by:
First off, I am sorry for cluttering this group with my inept questions, but I am stuck again despite a few hours of hair pulling. I have a function (below) that takes a list of html pages that...
409
by: jacob navia | last post by:
I am trying to compile as much code in 64 bit mode as possible to test the 64 bit version of lcc-win. The problem appears now that size_t is now 64 bits. Fine. It has to be since there are...
2
by: Terry Reedy | last post by:
SUBHABRATA, I recommend you study this excellent response carefully. castironpi wrote: It starts with a concrete test case -- an 'executable problem statement'. To me, this is cleared and...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...
0
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The...
0
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.