[noob question] References and copying

2006-06-09 Thread zefciu
Hello!

Where can I find a good explanation when does an interpreter copy the
value, and when does it create the reference.  I thought I understand
it, but I have just typed in following commands:

>>> a=[[1,2],[3,4]]
>>> b=a[1]
>>> b=[5,6]
>>> a
[[1, 2], [3, 4]]
>>> b
[5, 6]

And I don't understand it.  I thought, that b will be a reference to a,
so changing b should change a as well.  What do I do wrong.  And a
second question - can I create a reference to element of a list of
floating points and use this reference to change that element?

Greets to all PyFans
zefciu
-- 
http://mail.python.org/mailman/listinfo/python-list


Reuseable iterators - which is better?

2006-06-23 Thread zefciu
In the tutorial there is an example iterator class that revesrses the
string given to the constructor.  The problem is that this class works
only once, unlike built-in types like string.  How to modify it that it
could work several times?  I have tried two approaches.  They both work,
but which of them is stylistically better?

class Reverse: #original one
"Iterator for looping over a sequence backwards"
def __init__(self, data):
self.data = data
self.index = len(data)
def __iter__(self):
return self
def next(self):
if self.index == 0:
raise StopIteration
self.index = self.index - 1
return self.data[self.index]

class Reverse: #1st approach
"Reuseable Iterator for looping over a sequence backwards"
def __init__(self, data):
self.data = data
self.index = len(data)
def __iter__(self):
return self
def next(self):
if self.index == 0:
self.index = len(self.data) #Reset when previous
#
iterator goes out
raise StopIteration
self.index = self.index - 1
return self.data[self.index]

class Reverse: #2nd approach
"Reuseable Iterator for looping over a sequence backwards"
def __init__(self, data):
self.data = data
def __iter__(self):
self.index = len(self.data) #Reset as a part of iterator
# creation
return self
def next(self):
if self.index == 0:
raise StopIteration
self.index = self.index - 1
return self.data[self.index]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to run Python file?

2006-09-02 Thread zefciu
Pontus Ekberg wrote:
> mistral wrote:
> 
>> I have installed ActivePython
>> http://www.activestate.com/Products/ActivePython/
>> How I can run Python file, test.py?
> 
> $ python test.py
> 
> or
> 
> $ ./test.py (if test.py is executable)
> 
> 
Thats if you use un*x.  If you word under windows, the first would work,
but rather use some  IDE like IDLE or SPE than mess with the windows
command line.  Then you just load the file and run it from the menu.

zefciu
-- 
http://mail.python.org/mailman/listinfo/python-list


Inheritance doesn't work

2006-12-04 Thread zefciu
I have a problem with inheritance under python.  The class definition is  
longer, but the troublesome thing is:

 from PIL import Image
class MandelbrotImage (Image):
pass

I am getting the following error:
Traceback (most recent call last):
   File "", line 1, in ?
   File "mandelimage.py", line 3, in ?
 class MandelImage (Image):
TypeError: Error when calling the metaclass bases
 module.__init__() takes at most 2 arguments (3 given)


I am using python 2.4 from the Debian (Sid) packages.

Is it a bug, or am I doing something wrong?
zefciu

-- 
-BEGIN zefciu's GEEK CODE BLOCK-
Version: 3.12
GS d-(+) s+++:-- a-- C++ UL P- L++(+++) E--- W+ N++ o?
K? w-- M- V? PS-(--) PE++(+) Y PGP+ t 5 X R tv- b++
DI D- G e>+++ h!>-- y? UF+
--END zefciu's GEEK CODE BLOCK--
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Converting a c array to python list

2007-03-02 Thread zefciu
I have just read about buffer and array objects and I think one of them
could be fit for my need.  However there are two questions.

If i make a buffer from a part of dynamically allocated memory, what
would free it?  Should it be allocated with malloc or some
python-specific function?

How on earth can I create array object in C?

zefciu
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Converting a c array to python list

2007-03-03 Thread zefciu
Russell E. Owen wrote:

> 
> It might help to have a clearer idea of why you want to do this. 
> 

I am writing a Mandelbrot fractal generator with Tkinter interface.  Now
the generation works like this - there is a loop in python which
iterates through fractal's pixels and for each of them calls a functions
which checks if it belongs to Mandelbrot set or how many iterations does
it take for this point to bail out.  Then the python function sets the
pixel's colour according to the result.

I was testing it first with python function, written rather for
readibility not speed, using the builtin complex class.  It took about
90 s to generate a 1152x864 fractal.  Then I used a c function and it
took 14 s.  When I told it to my friend (grad student of informatics) he
said "And probably 90% of the time takes calling the function".

So I think, that maybe I should put the whole loop into c code.  But as
before the function returned only one integer at every call, now it
would have to return a rather large array of integers (maybe chars would
be enough).

zefciu
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Converting a c array to python list

2007-03-04 Thread zefciu
Dennis Lee Bieber wrote:

>   Written properly, all it returns is the address of that array data
> -- there is no massive copying of data..

I know :)  That's why I want to know how to write it properly.

zefciu
-- 
http://mail.python.org/mailman/listinfo/python-list


Curious behaviour of Tkinter object

2007-03-10 Thread zefciu
I am writing a program with python and Tkinter.  I have encountered a
mysterious problem with the whole application hanging itself (cannot be
stopped with ctrl-c, must be killed from another console).  I have done
several tests with interactive mode, and here what I noticed:
- the problem is with a class MandelSetWindow that I attach, as other
classes work properly

- the class can be initialized properly, but behaves strangely with
other windows.  Here is how to reproduce this bug:

* import Tkinter.Tk and this class
* create a Tk() instance and take a reference to it
* create an instance to this class (can use (None, None) as arguments)
and take a reference to it

Now everything looks normal.  Both references refer to objects like they
were created.  But try to e.g. withdraw() either the root Tk window or
this dialog.  You will notice that the other withdraws.  I really can't
understand why it happens like this.

zefciu
import Tkinter
from mandelpalette import MandelPalette

class MandelSetWindow(Tkinter.Toplevel, object):
"""A dialog window with main fractal settings"""
def __init__(self, settings, callback):
Tkinter.Toplevel.__init__(self)
self.callback = callback
self.textfields = {}
row = 0
for group in [("size", ["width", "height"], "pixel"),
("scale", ["XMin", "XMax", "YMin", "YMax"], ""),
("fractal parameters", ["bailout radius"], "")]:
Tkinter.Label(text = group[0]).grid(row = row, column = 0,
columnspan = 3)
row += 1
for param in group[1]:
Tkinter.Label(text = param).grid(row = row, column = 0)
self.textfields[param] = Tkinter.Entry(width = 10)
self.textfields[param].grid(row = row, column = 1)
Tkinter.Label(text = group[2]).grid(row = row, column = 2)
row += 1
Tkinter.Label(text="palette type").grid(row = row, column = 0)
self.palettebox = Tkinter.Listbox(height = 3)
for paltype in MandelPalette.palette_types:
self.palettebox.insert(Tkinter.END, paltype)
self.palettebox.grid(row = row, column = 1)
row += 1
Tkinter.Label(text="Iteration number").grid(row = row, column = 0)
self.textfields["iterations"] = Tkinter.Entry(width = 10)
self.textfields["iterations"].grid(row = row, column = 1)
row += 1
for butt in [("OK", self.__submit, 0), ("Cancel", self.__cancel, 1), 
("Reset", self.__reset, 2)]:
Tkinter.Button(text = butt[0], command = butt[1]).grid(row = row,
column = butt[2])
row += 1

def __getsettings(self):
result = {}
params = ["width", "height", "XMin", "XMax", "YMin", "YMax"]
for i in [("size", 2), ("scale", 4)]:
result[i[0]] = tuple([float(self.textfields[params.pop(0)].\
get()) for j in range(0, i[1])]) 
result["bailout"] = float(self.textfields["bailout radius"].get())
paltype = self.palettebox.get(self.palettebox.curselection())
iternumber = int(self.textfields["iterations"].get())
result["palette"] = mandelpalette.MandelPalette(iternumber, paltype, 1)
return result

settings = property(__getsettings)

def __submit(self):
self.callback(self.settings)


def __cancel(self):
pass
def __reset(self):
pass
def __fill(self, settings):
pass
class MandelPalette(list):
def __init__(self, size, type, cycles = 1):
try:
self.palette_types[type](self, size, cycles)
except KeyError:
raise ValueError("This palette type is not implemented")

def __genegray(self, size, cycles):
size += 1 # compensating for palette[0]
(levpercycle, remainder) = divmod(size, cycles)
for i in range(0, cycles):
if remainder: # remainder is compensated by first several cycles
remainder -= 1
levpercurrent = levpercycle + 1
else:
levpercurrent = levpercycle
step = 255.0 / (levpercurrent - 1) # if we don't add this -1 
 # we won't get white 
for j in range(0, levpercurrent):
level = int(j * step)
self.append((level, level, level))

def __generain(self, size, cycles):
pass

def __generand(self, size, cycles):
pass

palette_types = {"grayscale" : __genegray,
"rainbow" : __generain,
"random" : __generand}
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Hacking in python

2007-02-10 Thread zefciu
enes naci wrote:
> 
> i would like to know about hacking in python too whether its illegal or
> not is not the point and anyway it doesn't mean i'm gong to use it.
> 

If you mean hacking as modyfying the code of interpreter of libraries -
it is perfectly legal, as Python is Open Source.

If you mean hacking as cracking into computer systems, then what's the
difference if it's with Python or anything else.

If you mean hacking as gaining excellency in programming - then why
should it be?

Greets
zefciu
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: builtin set literal

2007-02-20 Thread zefciu
Paul Rubin wrote:
> There's even a sentiment in some pythonistas to get rid of the [] and {}
> notations for lists and dicts, using list((1,2,3)) and dict((1,2),(3,4))
> for [1,2,3] and {1:2, 3:4} respectively.

Wow.  This makes Python twice more LISPy, than <1, 2, 3> and {-} make it
C-ish and Perlish.

Frop Python-zen:
Simple is better than complex.
Flat is better than nested.

Sets are good.  Sets are fun.  Sets are pythonish (the programmer codes
the logical side of a data structure, bothering less 'bout the
technical).  I think, they deserve their literal notation.

zefciu
-- 
http://mail.python.org/mailman/listinfo/python-list


SystemError: new style getargs format but argument is not a tuple

2007-02-26 Thread zefciu
I am trying to embed a c function in my python script for a first time.
 When I try to call it I get an error

SystemError: new style getargs format but argument is not a tuple

Guido said on some mailing list, that it is probably an effect of the
lack of METH_VARARGS in the functions' array, but it's ok in my source
code.  Here is the full code:

#include 

static PyObject * mandelpixel(PyObject *self, PyObject *args)
{
double z_real = 0, z_imag = 0, z_real2 = 0, z_imag2 = 0, c_real,
c_imag, bailoutsquare;
int iteration_number;
register int i;
PyObject coord;
if (!PyArg_ParseTuple(args, "Oid", &coord, &iteration_number,
&bailoutsquare))
return NULL;
if (!PyArg_ParseTuple(&coord, "dd", &c_real, &c_imag))
return NULL;



for(i = 1; i <= iteration_number; i++)
{
z_imag = 2 * z_real * z_imag + c_imag;
z_real = z_real2 - z_imag2 + c_real;
z_real2 = z_real * z_real;
z_imag2 = z_imag * z_imag;
if (z_real2 + z_imag2 > bailoutsquare)
return Py_BuildValue("i", i);
}
return Py_BuildValue("i", 0);
}

static PyMethodDef MandelcMethods[] =
{
{
"mandelpixel", mandelpixel, METH_VARARGS, "check the pixel for
Mandelbrot set"
},
{
NULL, NULL, 0, NULL
}
};

PyMODINIT_FUNC initmandelc(void)
{
(void) Py_InitModule ("mandelc", MandelcMethods);
}

int main(int argc, char **argv)
{
Py_SetProgramName(argv[0]);
Py_Initialize();
initmandelc();
return 0;
}

Greets
zefciu
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: SystemError: new style getargs format but argument is not a tuple

2007-02-26 Thread zefciu
Thinker wrote:
> zefciu wrote:
>>> I am trying to embed a c function in my python script for a first
>>> time. When I try to call it I get an error
>>>
>>> SystemError: new style getargs format but argument is not a tuple
>>>
>>> Guido said on some mailing list, that it is probably an effect of
>>> the lack of METH_VARARGS in the functions' array, but it's ok in my
>>> source code. Here is the full code:

> Is coord always tuple?

Yes it is.  The script launches it with tuple and two numeric arguments.
 On the other hand when I try it in interactive mode with
mandelpixel((1,1), 1, 1) it segfaults, which I completely don't understand.

zefciu
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: SystemError: new style getargs format but argument is not a tuple

2007-02-26 Thread zefciu
Thinker wrote:

> It should be "PyObject *coord;" .
> Maybe, it is what is wrong with your program!
> 
>
Should it?  The gcc shows me a warning then:

warning: 'coord' is used uninitialized in this function

and during the execution I get the same error *plus* a segfault.

zefciu
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: SystemError: new style getargs format but argument is not a tuple

2007-02-26 Thread zefciu
Thinker wrote:

> You can add some printf() to throw out messages to make sure where the
> program stop at.
> If you can compile the module with debug information and use gdb to
> backtrace dump file,
> it would be useful.

Did it.  The arguments are parsed, but the coord tuple isn't.  But can
PyArg_ParseTuple be used to tuples other than function arguments?  If
not, what should I use?

zefciu
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: SystemError: new style getargs format but argument is not a tuple

2007-02-26 Thread zefciu
Thinker wrote:

> Since PyArg_ParseTuple() is supposed to parse arguments, I recommand you
> to use PyTuple_GetItem() or PyTuple_GET_ITEM().

Ok.  Now I do it this way:

c_real = PyFloat_AsDouble(PyTuple_GetItem(coord,0));
c_imag = PyFloat_AsDouble(PyTuple_GetItem(coord,1));

And it worked... once.  The problem is really funny - in the interactive
the function fails every second time.

>>> mandelpixel((1.5, 1.5), 9, 2.2)
args parsed
coord parsed
ii3
>>> mandelpixel((1.5, 1.5), 9, 2.2)
TypeError: bad argument type for built-in operation
>>> mandelpixel((1.5, 1.5), 9, 2.2)
args parsed
coord parsed
ii3
>>> mandelpixel((1.5, 1.5), 9, 2.2)
TypeError: bad argument type for built-in operation

etcaetera (the "args parsed" "coord parsed" and "i" are effect of
printfs in the code, as you see when it fails, it doesn't even manage to
parse the arguments.

zefciu
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: SystemError: new style getargs format but argument is not a tuple

2007-02-26 Thread zefciu
Ziga Seilnacht wrote:

> The second example uses your approach and is a bit more cumbersome,
> but still works. Could you post your current version of the code?
> I don't understand where your problem could be.

I think, there's no need to.  Now I understand :)

> if (!PyArg_ParseTuple(args, "Oid", &coord,
>&iteration_number, &bailoutsquare))

There was no ampersand in my version before coord.  I thought that as
coord is already a pointer, PyArg_ParseTuple will want it, not the
pointer to the pointer.

Now it works, but I will of course change it to get the simpler
parenthesised version as in your Example 1.

Great thanks :D

zefciu
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Add images together

2007-02-26 Thread zefciu
iceman wrote:
> a)Yes, I am using PIL.
> b)The color of each pixel over a sequence of frames
> 


If you want to add numerical values of each pixel's colour then itereate
through the pixels using nested for loops.  But I (and I thing the rest
of people here) can't be sure, what in fact you are trying to do.
Please provide us with further info - what are you working at?

zefciu
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: os.system and quoted strings

2007-02-27 Thread zefciu
svata wrote:
> Hello,
> 
> as I'm new to python I've stumbled accros os.system and its not very
> well documented usage.
> 
> I use Win XP Pro and Python 2.5.
> 
> Here is the code snippet:
> 
> --
> 
> import time
> import os
> 
> dir = "C:\\Documents and Settings\\somepath\\"
> fileName = time.strftime("%d%m%Y")
> os.system('gvim dir+fileName+".txt"')
> 
> ---
> 
> The problem is that concatenated variable dir+fileName doesn't get
> expanded as expected.
> 
> Is there anything I omitted?
> 
> svata
> 

The way you write it, Python has no idea that dir and fileName are
variables, not literal parts of the string.  You should put those names
outside the quotation marks, or better us the % format operator as
Sriram showed
you, or even better use os.path module.  Here is the reference:
http://docs.python.org/lib/module-os.path.html

zefciu
-- 
http://mail.python.org/mailman/listinfo/python-list


Converting a c array to python list

2007-03-01 Thread zefciu
Hi!

I want to embed a function in my python application, that creates a
two-dimensional array of integers and passes it as a list (preferably a
list of lists, but that is not necessary, as the python function knows
the dimensions of this array).  As I read the reference, I see, that I
must first initialize a list object and then item-by-item put the values
to the list.  Is there any faster way to do it?  And is it worth to
implement?  The same problem is resolved in the current version by
calling a smaller c function (that counts just one element of the array)
many times.  Will it add much performance to the process?

zefciu
-- 
http://mail.python.org/mailman/listinfo/python-list