Many newbie questions regarding python

Rogério Brito rbrito at ime.usp.br
Fri Oct 8 01:10:14 CEST 2010


Hi there.

I am used to some languages like C, but I am just a complete newbie with Python
and, while writing some small snippets, I had encountered some problems, with
which I would sincerely appreciate any help, since I appreciate this language to
write my "running pseudocode in" and I am seriously thinking of using it to
teach some algorithms classes.

1 - The first issue that I am having is that I don't seem to be able to, say,
use something that would be common for people writing programs in C: defining a
one-dimensional vector and only initializing it when needed.

For instance, in C, I would write something like:

int v[20];
for (i = 0; i < 20; i++)
    v[i] = 0;

Note that I only define the vector v (and its size) at the beginning but
initialize it latter during the code per-se.

My first try to write it in Python was something like this:

v = []
for i in range(20):
    v[i] = 0

Unfortunately, this doesn't work, as I get an index out of bounds when trying to
index the v list. Of course, the main difference between the two snippets is
that, in C, I declared v to have 20 positions, while in python I initialized it
to be the empty list and, indeed, it has an empty set of indexes.

What is the Pythonic way of writing code like this? So far, I have found many
alternatives and I would like to write code that others in the Python community
would find natural to read. Some of the things that crossed my mind:

    v = [0 for i in range(20)]

    v = [0] * 20

    v = []
    for i in range(20): v.append(0)

What should I prefer? Any other alternative?

If possible, I would like to simply declare the list and fill it latter in my
program, as lazily as possible (this happens notoriously when one is using a
technique of programming called dynamic programming where initializing all
positions of a table may take too much time in comparison to the filling of the
array).


2 - If I declare a class with some member variables, is is strictly necessary
for me to qualify those members in a method in that class? For instance, if I
define:

class C:
    f = 1
    def g(self):
        return f

I get an annoying message when I try to call the g method in an object of type
C, telling me that there's no global symbol called f. If I make g return self.f
instead, things work as expected, but the code loses some readability.

Is there any way around this or is that simply "a matter of life"?

I have some other questions, but I will save them for latter.

Please, keep in mind that I am a newbie in Python. Despite that, I am enjoying
the little that I know.


Thank you very much in advance,

-- 
Rogério Brito : rbrito@{ime.usp.br,gmail.com} : GPG key 4096R/BCFCAAAA
http://rb.doesntexist.org : Packages for LaTeX : algorithms.berlios.de
DebianQA: http://qa.debian.org/developer.php?login=rbrito%40ime.usp.br



More information about the Python-list mailing list