newbie question convert C to python
Adam DePrince
adam at cognitcorp.com
Tue Feb 15 20:07:56 EST 2005
On Tue, 2005-02-15 at 11:03, Steven Bethard wrote:
> Paul Rubin wrote:
> > doodle4 at gmail.com writes:
> >
> >>How do i handle this piece of code in python:
> >>
> >># define vZero 15
> >># define vOne 20
> >>
> >>unsigned int vTable[Zero][One]
> >>
> >>if(vGroup[vZero][vOne] == 0)
> >> {
> >> vGroup[vZero][vOne]--
> >> .....
> >> .....
> >> }
> >
> > Simplest might be with a dictionary:
> >
> > vGroup = {} # I assume you meant vGroup not vTable
> > if vGroup[(vZero, vOne)] == 0:
> > vGroup[(vZero, vOne)] -= 1
> > .....
> > .....
>
> Or, if you like, the parentheses are unnecessary:
>
> vGroup = {}
> if vGroup[vZero, vOne] == 0:
> vGroup[vZero, vOne] -= 1
> .....
>
> This (or the semantically identical version with parentheses) is
> definitely the best approach if you expect to have a lot of empty spots
> in your table.
>
> STeVe
One of the problems I see is the access of uninitialized values. In C,
you *can* read these and it isn't a bad idea if you used memset, calloc
or friends. If I know for sure this will be sparse, I'd reproduce it in
python like this.
vTable = []
for x in xrange( vZero ):
vTable.append( [0,] * vOne )
Now you have a vZero x vOne "array" of zeros. Treat it as you would
such a creature in C ...
vTable[0][0] = 1
or whatever you want to do.
I've seen this question before. Lot in the archives for the subject "2D
array" from Dec 7th 2004 - Dec 10th 2004.
Steven and I recommended roughly opposite solutions at the time :-)
Adam DePrince
More information about the Python-list
mailing list