how to get a formatted string?

2007-09-04 Thread Ginger
like format function in Visual Basic, 
format("##.##%",0.3456) ==>>  34.56%
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Text processing and file creation

2007-09-05 Thread Ginger
file reading latency is mainly caused by large reading frequency, so reduction 
of the frequency of file reading may be way to solved your problem.
u may specify an read bytes count for python file object's read() method, some 
large value(like 65536) can be specified due to ur memory usage, and u can 
parse lines from read buffer freely.

have fun!

- Original Message - 
From: "Shawn Milochik" <[EMAIL PROTECTED]>
To: 
Sent: Thursday, September 06, 2007 1:03 AM
Subject: Re: Text processing and file creation


> On 9/5/07, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote:
>> I have a text source file of about 20.000 lines.
>> >From this file, I like to write the first 5 lines to a new file. Close
>> that file, grab the next 5 lines write these to a new file... grabbing
>> 5 lines and creating new files until processing of all 20.000 lines is
>> done.
>> Is there an efficient way to do this in Python?
>> In advance, thanks for your help.
>>
> 
> 
> I have written a working test of this. Here's the basic setup:
> 
> 
> 
> 
> open the input file
> 
> function newFileName:
>generate a filename (starting with 1.tmp).
>If filename exists, increment and test again (0002.tmp and so on).
>return fileName
> 
> read a line until input file is empty:
> 
>test to see whether I have written five lines. If so, get a new
> file name, close file, and open new file
> 
>write line to file
> 
> close output file final time
> 
> 
> Once you get some code running, feel free to post it and we'll help.
> 
>
-- 
http://mail.python.org/mailman/listinfo/python-list


how to install python2.5.1 in a amd64 redhat linux?

2007-09-06 Thread Ginger
[EMAIL PROTECTED] make install
gcc -pthread -c -fno-strict-aliasing -DNDEBUG -g -O3 -Wall -Wstrict-prototypes  
-I. -I./Include   -DPy_BUILD_CORE -o Modules/python.o ./Modules/python.c
In file included from Include/Python.h:57,
 from Modules/python.c:3:
Include/pyport.h:734:2: #error "LONG_BIT definition appears wrong for platform 
(bad gcc/glibc config?)."
make: *** [Modules/python.o] Error 1

 
   Thanks and Regards,
Ginger-- 
http://mail.python.org/mailman/listinfo/python-list

anybody has py modules emulating symbian 60 on PC?

2007-09-10 Thread Ginger
like appuifw/graphics/sysinfo modules,
i've get some primary modules of these, they do what they did on S60 platform. 
u can get them from http://pdis.hiit.fi/pdis/
but these modules i get are rather simple ones, and a full emulation is needed 
..., so anyone who has it, plz send me a copy, with my appreciation.

thanks and regards
Ginger

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


Re: command-line arguments in IDLE

2007-11-07 Thread Ginger
it does have one in activepython
 
   Thanks and Regards,
Ginger
- Original Message - 
From: "Russ P." <[EMAIL PROTECTED]>
To: 
Sent: Wednesday, November 07, 2007 8:56 AM
Subject: command-line arguments in IDLE


> Is it possible to pass command-line arguments when running a program
> in IDLE? The "Run" menu does not seem to provide that option. Thanks.
> 
> 
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Threads vs Processes

2006-07-26 Thread Chance Ginger
On Wed, 26 Jul 2006 10:54:48 -0700, Carl J. Van Arsdall wrote:

> Alright, based a on discussion on this mailing list, I've started to 
> wonder, why use threads vs processes.  So, If I have a system that has a 
> large area of shared memory, which would be better?  I've been leaning 
> towards threads, I'm going to say why.
> 
> Processes seem fairly expensive from my research so far.  Each fork 
> copies the entire contents of memory into the new process.  There's also 
> a more expensive context switch between processes.  So if I have a 
> system that would fork 50+ child processes my memory usage would be huge 
> and I burn more cycles that I don't have to.  I understand that there 
> are ways of IPC, but aren't these also more expensive?
> 
> So threads seems faster and more efficient for this scenario.  That 
> alone makes me want to stay with threads, but I get the feeling from 
> people on this list that processes are better and that threads are over 
> used.  I don't understand why, so can anyone shed any light on this?
> 
> 
> Thanks,
> 
> -carl

Not quite that simple. In most modern OS's today there is something
called COW - copy on write. What happens is when you fork a process
it will make an identical copy. Whenever the forked process does
write will it make a copy of the memory. So it isn't quite as bad.

Secondly, with context switching if the OS is smart it might not 
flush the entire TLB. Since most applications are pretty "local" as
far as execution goes, it might very well be the case the page (or 
pages) are already in memory. 

As far as Python goes what you need to determine is how much 
real parallelism you want. Since there is a global lock in Python
you will only execute a few (as in tens) instructions before
switching to the new thread. In the case of true process you 
have two independent Python virtual machines. That may make things
go much faster.

Another issue is the libraries you use. A lot of them aren't 
thread safe. So you need to watch out.

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


Re: singleton decorator

2006-08-08 Thread Chaz Ginger
[EMAIL PROTECTED] wrote:
> Andre Meyer:
>> What is the preferred pythonic way of implementing singleton elegantly?
> 
> Maybe to just use a module.
> 
> Bye,
> bearophile
> 
Here is some sample code for both singleton classes and named classes 
that I use:

> class Singleton(type):
> """
> This class will allow only one instance of a type
> regardless of the initialization arguments.
> """
> def __init__(self, *args, **kwargs):
> """
> This is done when the class is defined.
> """
> type.__init__(self, *args, **kwargs)
> self._instance = None
> 
> def __call__(self, *args, **kwargs):
> """
> This is called when the class is instantiated.
> """
> if not self._instance : self._instance = 
> type.__call__(self,*args,**kwargs)
> return self._instance
> 
> class namedSingleton(type):
> """
> This class will allow a different singleton per initialization
> argument list.  This implementation does not take into account
> variations in the keyword args.
> """
> def __init__(self, *args, **kwargs):
> """
> This is executed when the class is first defined.
> """
> type.__init__(self, *args, **kwargs)
> self._instances = {}
> 
> def __call__(self, *args, **kwargs):
> """
> This is called when the class is instantiated.
> """
> if not args in self._instances:
> self._instances[args] = type.__call__(self, *args,**kwargs )
> return self._instances[args]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Global Objects...

2006-08-16 Thread Chaz Ginger
KraftDiner wrote:
> I have a question..
> 
> myGlobalDictionary = dictionary()
> 
> 
> class someClass:
>def __init__(self):
>   self.x = 0;
>def getValue(self, v)
>   myGlobalDictionary.getVal(v)
> 
> 
> myGlobalDictionary doesn't seem to be visible to my someClass methods.
> Why?  What should I do?
> 
Is it an oversight that you forgot the ':' on the getValue definition?
You also forgot to do the return. I say the code should look like:

def getValue(self,v) :
return myGlobalDictionary[v]

I am also confused as to what getVal() does.

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


Re: key not found in dictionary

2006-08-22 Thread Chaz Ginger
KraftDiner wrote:
> I have a dictionary and sometime the lookup fails...
> it seems to raise an exception when this happens.
> What should I do to fix/catch this problem?
> 
> desc = self.numericDict[k][2]
> KeyError: 589824   < This is the error that is being produced,
> because there is no key
> 589824.
> 

As stated you can wrap the access in the try - except - else statement, 
as in

try:
  foo['bar']
except :
  # Handle the error.
  pass
else :
  # We have it, so use it...
  print foo['bar']

Or you can use the has_key() and test it first. For example

  if foo.has_key('bar'):
print 'we have it'
  else :
print 'we don't have bar.'

That'll do it for me.

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


Re: Python component model

2006-10-09 Thread Chaz Ginger
Edward Diener No Spam wrote:
> [EMAIL PROTECTED] wrote:
>> Edward> The definition of a component model I use below is a class
>> which
>> Edward> allows properties, methods, and events in a structured way
>> which
>> Edward> can be recognized, usually through some form of introspection
>> Edward> outside of that class. This structured way allows visual
>> tools
>> Edward> to host components, and allows programmers to build
>> applications
>> Edward> and libraries visually in a RAD environment.
>>
>> ...
>> Edward> I believe that Python should have a common components
>> model for
>> Edward> all RAD development environments, as that would allow the
>> Python
>> Edward> programmer to create a set of classes representing components
>> Edward> which would work in any environment.
>>
>> Having never used java or .NET I'm not sure what you're looking for. 
>> Does
>> Python's current introspection not work?  Is it someone too unstructured
>> (whatever "structured" means)?  Can you give a simple example?
> 
> In the typical RAD development environment, a particular component model
> allows one to drop components, which are classes corresponding to a
> particular inner representation which tells the development environment
> what are the "properties" and "events" of that component, and
> subsequently set "properties" for that component and add handlers for
> its "events" visually.
> 
> Subsequently When the components are instantiated at run-time, the
> particular "properties" are automagically set and the particular
> "events" are automagically tied to event handlers in other classes (
> usually a window, or form, although it can be in any other class which
> can handle events ). How this "automagically" is done depends on the
> visual development environment.
> 
> I find it very neat that I, the end-user of the component, does not have
> to write the boiler-plate code to set "properties" and hook up "events"
> and can do this visually. I realize that others may find this
> unimportant. But in a visual environment where not only non-viusual
> components are involved, but also visual GUI components are, this also
> allows the visual look of a particular window ( form or screen if you
> like ) to be composed automatically. At the same time hooking non-visual
> components automagically at design time so that they are connected at
> run-time to event handlers is also very nice.
> 
> In order to make such a system work, the visual RAD environment needs to
> know what in a class makes it a component, and what in that components
> specifies the "properties" and "events" for which it will automagically
> setup the correct "code" which works at run-time. Without a component
> model to tell it these things, it can not work to produce the
> boiler-plate code necessary to set "properties" and hook event handlers
> to an event.
> 
> In JavaBeans, for Java, and the System.ComponentModel namespace, as well
> as properties, delegates, and events in .Net, there exists a common
> component model which defines, in these environments, what a components
> is so that the visual RAD development can do its magic.
> 
> I realize that many Python programmers don't see the necessity for
> having a RAD visual devlopment environment doing for them what they can
> do by hand in their Python code, particularly in the constructor to
> classes. But there are people who have used such a RAD model,
> particularly when setting up a GUI application or Web application, who
> appreciate the ease of use of such a RAD visual environment, especially
> in the area of dropping visual controls on a window and having that
> window appear at run-time with the particular look which they have
> visually setup at design time. But even beyond the more common visual
> setup of a window or web page, a visual RAD environment allows the
> end-user programmer to visually create boiler-plate code for setting the
> "properties" and "events" of non-visual classes, which make up the
> greater part of the internal logic of any given program.
> 
> More importantly a common component model, which works in any language's
> visual RAD environment, enables the development and re-use of components
> which are as easily used as dropping that component from a component
> palette onto a visual container, usually a representation of a run-time
> window, and setting it's "properties" and/or "events". The visual
> manipulation of components does not preclude making manipulations at
> run-time through code also if necessary, and all visual environements
> allow the setting of "properties" and "events" at run-time also in the
> usual way.
> 
> If one has used Borland's Delphi or C++ Builder IDEs, or Sun's NetBeans
> or IBM's Eclipse for Java, or Microsoft's Visual Studio for .Net, one
> knows what I mean as far as a visual RAD environment. All of these are
> made possible by a common component model which different development
> environments c

Re: Exploiting Dual Core's with Py_NewInterpreter's separated GIL ?

2006-11-07 Thread Chaz Ginger
Joe Seigh wrote:
> Martin v. Löwis wrote:
>> You still didn't say what you would suggest to make it thread-safe
>> again; most likely, you proposal would be to add locking. If I
>> understand Joe's approach correctly, he has a solution that does
>> not involve locking (although I don't understand how it works).
>>
> Sun had applied for a patent on it.  You can go to the
> uspto search page here http://www.uspto.gov/patft/index.html
> and look for
> 
> 20060218561 Code preparation technique employing lock-free pointer
> operations
> 20060037026 Lightweight reference counting using single-target
> synchronization
> 
> Click on the images link on the patent application where the illustrations
> are which show the concepts probably better than the text.
> 
> The first one above is actually a continuation patent on three different
> techniques.  One using double wide compare and swap, one using ROP (Repeat
> Offender Problem), a form of PDR, and one using DCAS (compare and swap
> of two separate locations) which only exists on MC68020 and MC68030
> processors.
> 
Check out the work in the '80s from the NYU Ultra project. They did a
great deal of work on using atomic incr/decr for all sorts of algorithms
 to get around locking on parallel processors.

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


Re: Python to C converter

2006-06-05 Thread Chance Ginger
If you are looking for a "real" python to C, well in this case
C++ look for the shedskin compiler. It will take a rather
nice subset of Python and generate C++ code from it. 

It is still rather experimental but I have been using it.

Chance G.

On Mon, 05 Jun 2006 07:19:39 -0700, Fuzzyman wrote:

> 
> gene tani wrote:
>> Rene Pijlman wrote:
>> > [EMAIL PROTECTED]:
>> > >I have an application return in python. I want this to be
>> > >converted to C.
>> >
>> > http://www.python.org/doc/faq/general/#can-python-be-compiled-to-machine-code-c-or-some-other-language
>> >
>>
>> http://pyfaq.infogami.com/can-python-be-compiled-to-machine-code-c-or-some-other-language
>> shd probably mention Shedskin, boost, ctypes, any others?
> 
> The PyPy LLVM backend will compile Python code to C.
> 
> Also Pyrex can do a bit more than just integrate C with Python, AFAIK
> it *can* compile some Python to C - although with very little speed
> advantage if you don't use native C types.
> 
> Fuzzyman
> http://www.voidspace.org.uk/python/index.shtml

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


Re: Python to C converter

2006-06-07 Thread Chance Ginger
Isn't Pyrex for writing extensions to Python? As for PyPy, I 
didn't scroll down far enough to see the compiler info. It
does say it is Python written in Python at the top.

Shedskin is nothing but a compiler.

On Wed, 07 Jun 2006 19:13:27 +0200, Carl Friedrich Bolz wrote:

> Chance Ginger wrote:
>> If you are looking for a "real" python to C, well in this case
>> C++ look for the shedskin compiler. It will take a rather
>> nice subset of Python and generate C++ code from it. 
> 
> 
> In which sense is shedskin a more "real" python to C/C++ compiler than 
> some of the other mentioned projects? As most of the others (PyPy, 
> Pyrex), Shedskin works only for a small number of Python programs that 
> don't mix types too wildly.
> 
> BTW: While the RPython (the subset of the Python language that PyPy can 
> compile) might not be extremely advanced, using it gives you a number of 
> very interesting features: like having the resulting program been 
> enhanced to not use the C stack (for deeply recursive code), using 
> different garbage collection strategies...
> 
> Cheers,
> 
> Carl Friedrich Bolz

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


Re: Way for see if dict has a key

2006-06-30 Thread Chance Ginger
On Fri, 30 Jun 2006 10:19:46 +, Michele Petrazzo wrote:

> Hi ng,
> what the preferred way for see if the dict has a key?
> We have a lot of solutions:
> 
> key in dict
> key in dict.keys()
> dict.has_key(key)
> ...
> 
> but what the better or the more "pythonic"?
> 
> Thanks,
> Michele

It is a religious call


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


When is a subclass not right?

2006-08-24 Thread Chaz Ginger
I was writing some code that used someone else class as a subclass. He 
wrote me to tell me that using his class as a subclass was incorrect. I 
am wondering under what conditions, if ever, does a class using a 
subclass not work.

Here is an example. For instance the original class might look like:

class A :
  def __init__(self,arg) :
self.foo = arg
  def bar(self) :
return self.foo


And I defined a class B1 which looked like:


class B1(A);
  def __init__(self,a1,a2) :
self.c = a1
A.__init__(self,ag)


He said I should use it this way:

class B2:
  def __init__(self,a1,a2):
self.c = a1
self.t = A(a2)

  def bar(self) :
self.t.bar()


Other than the obvious difference of B2 having an attribute 't', I can't 
see any other obvious differences. Is there something I am missing?

TIA
Chaz

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


Re: When is a subclass not right?

2006-08-24 Thread Chaz Ginger
Fredrik Lundh wrote:
> please don't hit reply to arbitrary messages when you're posting new
> messages; it messes up the message threading.
> 
> Chaz Ginger wrote:
> 
>> I was writing some code that used someone else class as a subclass. He 
>> wrote me to tell me that using his class as a subclass was incorrect. 
>> I am wondering under what conditions, if ever, does a class using a 
>> subclass not work.
> 
> your terminology is confused: if you inherit from another class, *your* 
> class is the subclass, while the class you inherit from is known as a 
> "base class" or "super class".
> 
> a subclass will share the instance namespace with the base class, which 
> means, among other things, that you may accidentally override internal 
> attributes and methods, and thus break the base class.
> 
> and even if it appears to work now, it may break when you upgrade the 
> base class.  or when you end up in a code path that you haven't tested 
> before.
> 
> 
> 
Sorry for the threading screw up. I thought I had just hit the write button.

I understand when my class overrides the super class. But that would 
just be "normal" class related things. I was wondering if there was 
something more subtle I am missing in Python class handling.

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


Re: When is a subclass not right?

2006-08-24 Thread Chaz Ginger
Gabriel Genellina wrote:
> At Thursday 24/8/2006 16:23, Chaz Ginger wrote:
> 
>> I was writing some code that used someone else class as a subclass. He
>> wrote me to tell me that using his class as a subclass was incorrect. I
>> am wondering under what conditions, if ever, does a class using a
>> subclass not work.
>>
>> class B1(A);
>>   def __init__(self,a1,a2) :
>> self.c = a1
>> A.__init__(self,ag)
>>
>> class B2:
>>   def __init__(self,a1,a2):
>> self.c = a1
>> self.t = A(a2)
>>
>>   def bar(self) :
>> self.t.bar()
>>
>> Other than the obvious difference of B2 having an attribute 't', I can't
>> see any other obvious differences. Is there something I am missing?
> 
> Look any OO book for the difference between 'inheritance' and 
> 'delegation'. In short, you should inherit when B 'is an' A (a Car is a 
> Vehicle), and delegate/compose in other cases (a Car has an Engine; or 
> more precisely, a Car instance has an Engine instance).
> 
> 
> Gabriel Genellina
> Softlab SRL
> 
> 
> p5.vert.ukl.yahoo.com uncompressed Thu Aug 24 19:27:05 GMT 2006 
>
> __ Preguntá. Respondé. 
> Descubrí. Todo lo que querías saber, y lo que ni imaginabas, está en 
> Yahoo! Respuestas (Beta). ¡Probalo ya! http://www.yahoo.com.ar/respuestas

That is merely a logical use of OO after all when would a car and an 
orange be the same?

I was wondering more about the mechanics of Python: when does B1 show 
different characteristics than B2  (forgoing the obvious simple things, 
like 't' above).

Chaz


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


Re: Avoiding if..elsif statements

2006-08-25 Thread Chaz Ginger
unexpected wrote:
> I have a program where based on a specific value from a dictionary, I
> call a different function. Currently, I've implemented a bunch of
> if..elsif statements to do this, but it's gotten to be over 30 right
> now and has gotten rather tedious. Is there a more efficient way to do
> this?
> 
> Code:
> 
> value = self.dictionary.get(keyword)[0]
> 
> if value == "something":
> somethingClass.func()
> elsif value == "somethingElse":
> somethingElseClass.func()
> elsif value == "anotherthing":
> anotherthingClass.func()
> elsif value == "yetanotherthing":
> yetanotherthingClass.func()
> 
> Is it possible to store these function calls in a dictionary so that I
> could just call the dictionary value?
> 
Why not do it this way?

foo = 
{'something':somethingClass.func,'somethingelse':somethingelseClass.func)

if foo.has_key(value) :
foo[value]()
else :
raise OMG, "%s isn't known" % value



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


when is a != foo.a?

2006-08-28 Thread Chaz Ginger
I am somewhat new to Python (last year). As such I encounter little 
"gotchas" all the time. I am wondering is someone can explain this to me:

If have three simple files:

a.py -

foo = None
def a(b):
global foo
foo = b

b.py --

from a import foo
def b(): print foo

c.py --

import a
from b import b

print 'per a.a() ',a.foo
a.a(245)
print 'expect 245 ', a.foo
b()


If I run 'python c.py' I get the following printed out:


per a.a()  None
expect 245  245
None


That surprised me. If I change b.py to

import a
def b(): print a.foo

I get the following (which is what I expected originally):


per a.a()  None
expect 245  245
245


Can someone explain what is really going on here?

TIA,
Chaz
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: when is a != foo.a?

2006-08-28 Thread Chaz Ginger
Duncan Booth wrote:
> Chaz Ginger wrote:
> 
>> Can someone explain what is really going on here?
> 
> Think of 'from x import y' as an assignment. Roughly equivalent to:
> 
>y = sys.modules['x'].y
> 
> (except of course you don't have to have imported sys, and it will load the 
> module 'x' if it hasn't already been imported.)
> 
>> b.py --
>>
>> from a import foo
> 
> In other words:
> 
>foo = a.foo
> 
> foo in module b is initialised from a.foo, but it is a separate variable. 
> So when a.foo is rebound that doesn't affect b.foo.
> 
>> def b(): print foo
>>
>> c.py --
>>
>> import a
>> from b import b
> 
> and here:
>b = b.b
> 
>> print 'per a.a() ',a.foo
>> a.a(245)
>> print 'expect 245 ', a.foo
>> b()
>>
> 
> 

Thanks, Duncan. It now makes sense.

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


Re: when is a != foo.a?

2006-08-28 Thread Chaz Ginger
John Machin wrote:
> Chaz Ginger wrote:
>> I am somewhat new to Python (last year). As such I encounter little
>> "gotchas" all the time. I am wondering is someone can explain this to me:
>>
>> If have three simple files:
>>
>> a.py -
>>
>> foo = None
>> def a(b):
>>  global foo
>>  foo = b
>>
>> b.py --
>>
>> from a import foo
>> def b(): print foo
>>
>> c.py --
>>
>> import a
>> from b import b
>>
>> print 'per a.a() ',a.foo
>> a.a(245)
>> print 'expect 245 ', a.foo
>> b()
>>
>>
>> If I run 'python c.py' I get the following printed out:
>>
>>
>> per a.a()  None
>> expect 245  245
>> None
>>
>>
>> That surprised me. If I change b.py to
>>
>> import a
>> def b(): print a.foo
>>
>> I get the following (which is what I expected originally):
>>
>>
>> per a.a()  None
>> expect 245  245
>> 245
>>
>>
>> Can someone explain what is really going on here?
> 
> You are, in a very roundabout fashion, effectively executing the
> following bindings:
> 
> a.foo = None # done when a is first imported
> b.foo = a.foo # done in module b by "from a import foo"
> a.foo = 245
> 
> So b.foo is bound to None, and a.foo is bound to 245. 
> 
> Cheers,
> John
> 

Thanks John. It is a lot different from the C and C++ world where you 
can hold a reference to something and use it. That is how I thought 
about what I was doing and learned it wasn't quite right! lol.

Thanks again.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: refering to base classes

2006-08-29 Thread Chaz Ginger
glenn wrote:
> hi - Im quite new to python, wondering if anyone can help me understand
> something about inheritance here. In this trivial example, how could I
> modify the voice method of 'dog' to  call the base class 'creatures'
> voice method from with in it?
> 
> class creature:
> def __init__(self):
> self.noise=""
> def voice(self):
> return "voice:" + self.noise
> 
> class dog(creature):
> def __init__(self):
> self.noise="bark"
> 
> def voice(self):
> print "brace your self:"
> 
> thanks
> glenn
> 
Try this:

class dog(creature):
.
def voice(self):
print "brace your self:"
creature.voice(self)

This should do it.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: refering to base classes

2006-08-29 Thread Chaz Ginger
Chaz Ginger wrote:
> glenn wrote:
>> hi - Im quite new to python, wondering if anyone can help me understand
>> something about inheritance here. In this trivial example, how could I
>> modify the voice method of 'dog' to  call the base class 'creatures'
>> voice method from with in it?
>>
>> class creature:
>> def __init__(self):
>> self.noise=""
>> def voice(self):
>> return "voice:" + self.noise
>>
>> class dog(creature):
>> def __init__(self):
>> self.noise="bark"
>>
>> def voice(self):
>> print "brace your self:"
>>
>> thanks
>> glenn
>>
> Try this:
> 
> class dog(creature):
> .
> def voice(self):
> print "brace your self:"
> creature.voice(self)
> 
> This should do it.
I did forget to mention that in 'dog"s' __init__ you had better call 
creature's __init__. You might make it look like this:

def __init__(self):
self.noise = 'bark'
creature.__init__(self)

There is another approach - using Superclass - but I will leave that 
exercise to the reader.

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


Re: refering to base classes

2006-08-29 Thread Chaz Ginger
Jason wrote:
> Chaz Ginger wrote:
>> Chaz Ginger wrote:
>>> glenn wrote:
>>>> hi - Im quite new to python, wondering if anyone can help me understand
>>>> something about inheritance here. In this trivial example, how could I
>>>> modify the voice method of 'dog' to  call the base class 'creatures'
>>>> voice method from with in it?
>>>>
>>>> class creature:
>>>> def __init__(self):
>>>> self.noise=""
>>>> def voice(self):
>>>> return "voice:" + self.noise
>>>>
>>>> class dog(creature):
>>>> def __init__(self):
>>>> self.noise="bark"
>>>>
>>>> def voice(self):
>>>> print "brace your self:"
>> I did forget to mention that in 'dog"s' __init__ you had better call
>> creature's __init__. You might make it look like this:
>>
>> def __init__(self):
>>  self.noise = 'bark'
>>  creature.__init__(self)
>>
> 
> There's a problem with Chaz's __init__() method.  Notice that the
> creature class's __init__ sets self.noise to the empty string.  In this
> case, the superclass's __init__() method should be called first:
> 
> class dog(creature):
> def __init__(self):
> creature.__init__(self)
> self.noise = "bark"
> def voice(self):
> print "brace your self:"
> creature.voice(self)
> 
>   --Jason
> 
Very trueI was showing him in "spirit only"...lol.


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


Re: refering to base classes

2006-08-30 Thread Chaz Ginger
glenn wrote:
>> Shouldn't that be
>>
>> beagle = animal.dog()
>>
>> to create an instance?
>>
>> We've all done it ...
> lol - actually Im confused about this - there seem to be cases where
> instantiaing with:
> instance=module.classname()
> gives me an error, but
> instance=module.classname
> doesnt - so I got into that habit, except for where I had a constructor
> with parameters - except now Im feeling foolish because I cant
> replicate the error - which suggests I didnt understand the error
> message properly in the first place... arrgh
> I guess thats just part of the process of gaining a new language.
> 
> glenn
> 

module.classname and module.classname() are two different things. If you 
use module.classname() you invoke the __new__ and __init__ methods in 
the class, and you might get an error from them.

On the other hand module.classname will always work, assuming classname 
really exists in module. What you get back is a sort of reference to the 
class itself and not an instance of it.

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


Re: refering to base classes

2006-08-30 Thread Chaz Ginger
Georg Brandl wrote:
> Chaz Ginger wrote:
>> glenn wrote:
>>>> Shouldn't that be
>>>>
>>>> beagle = animal.dog()
>>>>
>>>> to create an instance?
>>>>
>>>> We've all done it ...
>>> lol - actually Im confused about this - there seem to be cases where
>>> instantiaing with:
>>> instance=module.classname()
>>> gives me an error, but
>>> instance=module.classname
>>> doesnt - so I got into that habit, except for where I had a constructor
>>> with parameters - except now Im feeling foolish because I cant
>>> replicate the error - which suggests I didnt understand the error
>>> message properly in the first place... arrgh
>>> I guess thats just part of the process of gaining a new language.
>>>
>>> glenn
>>>
>>
>> module.classname and module.classname() are two different things. If 
>> you use module.classname() you invoke the __new__ and __init__ methods 
>> in the class, and you might get an error from them.
>>
>> On the other hand module.classname will always work, assuming 
>> classname really exists in module. What you get back is a sort of 
>> reference to the class itself and not an instance of it.
> 
> It is not a sort of reference to the class, it is *the class itself*.
> 
>  >>> class A:
> ... pass
> ...
>  >>> A
> 
>  >>>
> 
> Georg
A reference by any other name still smells as sweet! lol.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Naming conventions

2006-08-30 Thread Chaz Ginger
Neil Cerutti wrote:
> On 2006-08-30, Jean-Paul Calderone <[EMAIL PROTECTED]> wrote:
>> On Wed, 30 Aug 2006 14:22:16 +1000, Ben Finney <[EMAIL PROTECTED]> wrote:
>>> "glenn" <[EMAIL PROTECTED]> writes:
>>>
 Bruno Desthuilliers wrote:
> It might be better to use newstyle classes if you can. Also, the
> convention is to use CamelCase for classes names (unless you have
> a strong reason to do otherwise).
>>> Note that this style is more correctly called TitleCase, since the
>> Or StudlyCaps :)
> 
> The first time I saw StudlyCaps I thought it was the ugliest
> thing I'd ever seen.  Now I use it a lot. I still have trouble
> with GVR's preference for HTTPServer over HttpServer. The latter
> is, to me, easier to read and write.
> 

Personally I think so long as you are consistent in your coding style, 
be it httpserver, HttpServer or HTTPServer or any other variation, the 
reader will soon figure out what it means.

If you feel you are being held hostage to capitalized naming conventions 
you might want to consider having things end in ...Class or ...Instance. 
At least you would be doing what you say you want to do: making the code 
more maintainable. Otherwise I say just be consistent and don't let 
dogma get in the way.

All those that remember "Hungarian notation" please stand up!
-- 
http://mail.python.org/mailman/listinfo/python-list


Automatically installing libraries?

2006-09-18 Thread Chaz Ginger
Here is a problem I am trying to solve; I am sure there must be an easy 
way to do it and I just don't know how.

I have a rather large application that I am writing. To make it easy for 
the user to run I have them run a startup.py script. This script will 
try to load each of the third party libraries the application will need. 
If it is present, great. If it isn't, I would like to automatically 
install it. This is the heart of my problem: is there a Python 
equivalent to PERL's CPAN?

Peace,
Chaz
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: identifying new not inherited methods

2006-09-26 Thread Chaz Ginger
Steve Holden wrote:
> [EMAIL PROTECTED] wrote:
>> Hi,
>>
>> I am writing a library in which I need to find the names of methods
>> which are implemented in a class, rather than inherited from another
>> class. To explain more, and to find if there is another way of doing
>> it, here is what I want to do: I am defining two classes, say A and B,
>> as:
>>
>> class A(object):
>> def list_cmds(self):
>> 'implementation needed'
>> ?
>> def __init__(self):
>> ... (rest of class)
>>
>> class B(A):
>> def cmd1(self, args):
>> pass
>> def cmd2(self, args):
>> pass
>>
>> I need an implementation of list_cmds in A above so that I can get a
>> result:
>>
>>
> b=B()
> b.list_cmds()
>>
>> ['cmd1','cmd2']#order not important
>>
>> I will be happy if anybody can point to me any way of doing it, using
>> class attributes, metaclasses or otherwise. What I don't want to do is
>> modifying class B, which contains just the cmds, if possible.
>>
>> Many thanks in advance.
>>
> $ cat test01.py
> class A(object):
> def list_cmds(self):
> """return callable attributes from
>subclasses not present in main class."""
> Amethods = [m for m in dir(A) if callable(getattr(A, m))]
> return [m for m in dir(self.__class__)
> if callable(getattr(self.__class__, m))
>and m not in Amethods]
> def __init__(self):
> pass
> 
> class B(A):
> def cmd1(self, args):
> pass
> def cmd2(self, args):
> pass
> 
> print "A additionals:", A().list_cmds()
> print "B additionals:", B().list_cmds()
> 
> 
> [EMAIL PROTECTED] ~
> $ python test01.py
> A additionals: []
> B additionals: ['cmd1', 'cmd2']
> 
> [EMAIL PROTECTED] ~
> $
> 
> Hope this helps.
> 
> regards
>  Steve

You don't really want to use dir(A), since this will not pick up all the 
  classes that make up A.  Don't you want to use the MRO instead?

Chaz

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


Re: identifying new not inherited methods

2006-09-26 Thread Chaz Ginger
Steve Holden wrote:
> Chaz Ginger wrote:
>> Steve Holden wrote:
>>
>>> [EMAIL PROTECTED] wrote:
>>>
>>>> Hi,
>>>>
>>>> I am writing a library in which I need to find the names of methods
>>>> which are implemented in a class, rather than inherited from another
>>>> class. [...]
>>
>>
>> You don't really want to use dir(A), since this will not pick up all 
>> the   classes that make up A.  Don't you want to use the MRO instead?
>>
> Tell me, what won't appear in the dir() of A that *will* appear in the 
> dir() of a subclass of A? Seems to me you're trying to overcomplicate 
> things.
> 
> regards
>  Steve
You are right...I just never did a dir(class) before, instead relying on 
using the MRO to do the searching. dir(class) is certainly a lot 
simpler! Thanks.

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


Best way to handle large lists?

2006-10-03 Thread Chaz Ginger
I have a system that has a few lists that are very large (thousands or
tens of thousands of entries) and some that are rather small. Many times
I have to produce the difference between a large list and a small one,
without destroying the integrity of either list. I was wondering if
anyone has any recommendations on how to do this and keep performance
high? Is there a better way than

[ i for i in bigList if i not in smallList ]

Thanks.
Chaz
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Best way to handle large lists?

2006-10-03 Thread Chaz Ginger
I've done that and decided that Python's 'list comprehension' isn't a
way to go. I was hoping that perhaps someone had some experience with
some C or C++ library that has a Python interface that would make a
difference.

Chaz

Sybren Stuvel wrote:
> Bill Williams enlightened us with:
>> I don't know enough about Python internals, but the suggested
>> solutions all seem to involve scanning bigList. Can this presumably
>> linear operation be avoided by using dict or similar to find all
>> occurrences of smallist items in biglist and then deleting those
>> occurrences?
> 
> And how would that beat O(n)? Every element of bigList has to be
> scanned at one point, either to compare it to every earlier element in
> bigList and eliminate it, or to compare it to every element in
> smallList.
> 
> Run benchmarks on the suggestions, and see which is fastest for
> yourself.
> 
> Sybren
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Best way to handle large lists?

2006-10-03 Thread Chaz Ginger
Paul Rubin wrote:
> Sybren Stuvel <[EMAIL PROTECTED]> writes:
>>> I don't know enough about Python internals, but the suggested
>>> solutions all seem to involve scanning bigList. Can this presumably
>>> linear operation be avoided by using dict or similar to find all
>>> occurrences of smallist items in biglist and then deleting those
>>> occurrences?
>> And how would that beat O(n)? Every element of bigList has to be
>> scanned at one point, either to compare it to every earlier element in
>> bigList and eliminate it, or to compare it to every element in
>> smallList.
> 
> Maybe the application should use sets instead of lists for these
> collections.
What would sets do for me over lists?

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


Re: Best way to handle large lists?

2006-10-03 Thread Chaz Ginger
Larry Bates wrote:
> Chaz Ginger wrote:
>> I have a system that has a few lists that are very large (thousands or
>> tens of thousands of entries) and some that are rather small. Many times
>> I have to produce the difference between a large list and a small one,
>> without destroying the integrity of either list. I was wondering if
>> anyone has any recommendations on how to do this and keep performance
>> high? Is there a better way than
>>
>> [ i for i in bigList if i not in smallList ]
>>
>> Thanks.
>> Chaz
> 
> 
> IMHO the only way to speed things up is to know more about the
> actual data in the lists (e.g are the elements unique, can they
> be sorted, etc) and take advantage of all that information to
> come up with a "faster" algorithm.  If they are unique, sets
> might be a good choice.  If they are sorted, bisect module
> might help.  The specifics about the list(s) may yield a faster
> method.
> 
> -Larry
Each item in the list is a fully qualified domain name, e.g.
foo.bar.com. The order in the list has no importance. That is about all
there is to the list other than to say the number of items in a list can
top out about 10,000.

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


Re: Best way to handle large lists?

2006-10-03 Thread Chaz Ginger
Jeremy Sanders wrote:
> Jeremy Sanders wrote:
> 
>> Chaz Ginger wrote:
>>
>>> What would sets do for me over lists?
>> It's faster to tell whether something is in a set or dict than in a list
>> (for some minimum size).
> 
> As a footnote, this program
> 
> import random
> num = 10
> 
> a = set( range(num) )
> for i in range(10):
> x = random.randint(0, num-1) in a
> 
> completes in less than a second, whereas
> 
> import random
> num = 10
> 
> a = range(num)
> for i in range(10):
> x = random.randint(0, num-1) in a
> 
> takes a long time on my computer.
> 
> Jeremy
> 
Thanks Jeremy. I am in the process of converting my stuff to use sets! I
wouldn't have thought it would have made that big a deal! I guess it is
live and learn.

Peace,
Chaz
-- 
http://mail.python.org/mailman/listinfo/python-list


Packaging up a Python/Twisted Matrix application...

2007-01-04 Thread Chaz Ginger
I have a rather large Python/Twisted Matrix application that will be run 
on Windows, Linux and perhaps Macs. I was wondering if there are any 
tools that can be used to create an installer that will bring in Python, 
Twisted Matrix, my application libraries and anything else I need?

I have tried using ezsetup with no luck (it seems not everything can be 
installed with it). I was hoping to find something as nice (and 
complete) as Perl's CPAN but can't seem to find anything.

Does anyone have any recommendations?

Peace,
Chaz.
-- 
http://mail.python.org/mailman/listinfo/python-list


Writing an applilcation that can easily adapt to any language

2006-03-01 Thread Chance Ginger
I am rather new at Python so I want to get it right. What I am doing
is writing a rather large application with plenty of places that 
strings will be used. Most of the strings involve statements of
one kind or another. 

I would like to make it easy for the support people to port the
application from one language to another, German, Spanish, etc. 
Rather than make them search all over for the strings to replace
is there a library that I can use to make this all easier? I
keep thinking of resources in Java, as an example. Is there 
anything like it in Python?

Peace,
Chance.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Threads, signals and sockets (on UNIX)

2007-06-11 Thread Chaz Ginger
geoffbache wrote:
>> Twisted *should* be able to do this, as it uses non-blocking IO.
>>
>> http://twistedmatrix.com/trac/
> 
> Thanks for the tip. I'll take a look if nobody has any better
> suggestions.
> 
> It still seems to me that what I'm trying to do is essentially quite
> simple, and shouldn't require
> as large a tool as Twisted to fix it. Isn't Twisted basically for web
> applications?
> 
> Geoff
> 
You could probably use the Asyncore stuff to do it as well (with a lot
less stuff).

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


XMLRPC and SSL

2007-06-18 Thread Chaz Ginger
I have a web service that I built and it requires using SSL. I have 
found a few examples of clients using SSL but none that allow me to 
change the client's certificate or the chain of certificates the client 
will use to authenticate the server.

I was wondering if anyone knows of a good example of this?

TIA,
Chaz.
-- 
http://mail.python.org/mailman/listinfo/python-list


Minimal Linux system to run Python

2007-04-14 Thread Chaz Ginger
I have a need for the minimal Linux system to run Python. Basically I
want the system to boot up and instead of starting up Init/etc. I would
love it to run python (and a python script I have written).

Before embarking on doing it myself I was wondering if anyone knew of
just such a system?

Peace,
Chaz
-- 
http://mail.python.org/mailman/listinfo/python-list


Authenticating clients and servers

2007-04-15 Thread Chaz Ginger
I am writing a distributed server system using Python. I need to support
authentication and was wondering what approaches are available under
Python and what are the best practices.

Thanks in advance
Chaz
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Authenticating clients and servers

2007-04-15 Thread Chaz Ginger
Thomas Krüger wrote:
> Chaz Ginger schrieb:
>> I am writing a distributed server system using Python. I need to support
>> authentication and was wondering what approaches are available under
>> Python and what are the best practices.
> 
> Well, there are many ways of client authentication. To narrow it down it
> would be nice if your tell us something about the protocol you are
> planning to use.
> 
> Many protocols support an additional SSL/TLS-Layers (e.g. HTTP ->
> HTTPS). There you can use SSL certificate authentication. It may
> berequired to set up a small CA, but done right it is pretty secure.
> 
> Thomas
> 
I am leaning toward using Kerberos via GSS, but I am willing to listen
to other ideas. I've played around with TLS but the problem is that
updating the .PEM files can be a pain. I was also thinking about X509,
and was wondering if anyone has experience with it.

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


Using X509 (and TLSlite) authentication

2007-04-17 Thread Chaz Ginger
I have been looking for a server application as an example of how to use
TLSLite or PyOpenSSL X509 certificates for authentication. Does any one
have a pointer or two?

Peace,
Chaz
-- 
http://mail.python.org/mailman/listinfo/python-list


New beginner to python for advice

2006-05-22 Thread Minlar Ginger
HIi all:
I am a new beginner to  python, would you like give me some advice on
studying it?
Welcome to list some book on python for me.
Thanks a lot.

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


Writing 'C' structures out in cPickle format?

2006-03-14 Thread Chance Ginger
I have a problem that I am trying to solve. I have two different
systems - one written in C and another in Python. I would like the
two to exchange some information. 

On the Python side I decided to use cPickle. On the C side I would
write a library that can read the cPickle and generate the correct
C structure (the data is, more or less, self-describing) and visa
versa. 

I was wondering if anyone has done something like this before
and if so can they point me to information on how to easily do it?
The structures I am using on the C side are pretty simple (very
flat and using only integers and strings).
-- 
http://mail.python.org/mailman/listinfo/python-list


Detecting arguments of a function - possible?

2006-03-17 Thread Chance Ginger
I am trying to write a tool to examine a function (I'd like it
to work with pyc files only). So here are a few questions I 
have; any pointers would be very welcome.

Can I determine the number of arguments required of a function?
Is there a way to detect is the function will throw an exception
(I don't care under what conditions just that it is possible)?

Thanks in advance...
Chas.
-- 
http://mail.python.org/mailman/listinfo/python-list


Decorators, Identity functions and execution...

2006-04-09 Thread Chance Ginger
If I define a decorator like:

def t(x) :
def I(x) : return x
return I

and use it like:

@t(X)
def foo(a) :
# definition of foo...
pass

or maybe this:

@t(X)
@(Y)
def bar(a) :
# The definition of bar...


Will in encounter much of a penalty in executing 
'foo' or 'bar'? If so, is there a way to define
t such that Python knows it is the identity function
and short-circuit evaluation?

Thanks in advance.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Decorators, Identity functions and execution...

2006-04-09 Thread Chance Ginger
On Sun, 09 Apr 2006 09:51:18 +0200, Fredrik Lundh wrote:

> Chance Ginger" wrote:
> 
>> If I define a decorator like:
>>
>> def t(x) :
>> def I(x) : return x
>> return I
> 
> ... you get a syntax error.
> 

It isn't a syntax error...I tried it before I posted. In fact
def t(x) :
def I(x) : return x
return I

is correct.

>> and use it like:
>>
>> @t(X)
>> def foo(a) :
>> # definition of foo...
>> pass
> 
> that's also a syntax error.

Once again this isn't an error assuming you pass in a valid 'X'.


> 
>> or maybe this:
>>
>> @t(X)
>> @(Y)
>> def bar(a) :
>> # The definition of bar...
> 
> and that's not even fixable.
>

Again you are mistaken. If I say:

@t(1)
@t(2)
def bar(a) : pass

It is perfectly valid. 
>> Will in encounter much of a penalty in executing
>> 'foo' or 'bar'?
> 
> since foo is wrapped, calling foo will call your I function, which in
> turn calls the original foo.
> 
>> If so, is there a way to define t such that Python knows it is
>> the identity function and short-circuit evaluation?
> 
> if you don't want to wrap something, don't wrap it:
> 
> def t(x) :
> def I(x) :
> return x
> if date == friday:
> return x # don't wrap it
> return I # wrap it
> 
> 

Decorators are a way to add "syntactic" sugar to Python,
extending it in ways that make it useful for tools. What 
I am trying to do is lessen the impact on the time used
in executing Python code when I use some forms of decorators.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Decorators, Identity functions and execution...

2006-04-09 Thread Chance Ginger
First, thanks for the tip of 'tabs'. I keep forgetting
Outlook has some interesting rules about displaying text.

Thanks for the comment about happening at load time. That
resolved the problem (in my thinking)! I don't believe I
have an issue at all...

Peace,
CG.

On Sun, 09 Apr 2006 08:52:18 -0700, Carl Banks wrote:

> 
> Chance Ginger wrote:
>> On Sun, 09 Apr 2006 09:51:18 +0200, Fredrik Lundh wrote:
>>
>> > Chance Ginger" wrote:
>> >
>> >> If I define a decorator like:
>> >>
>> >> def t(x) :
>> >> def I(x) : return x
>> >> return I
>> >
>> > ... you get a syntax error.
>> >
>>
>> It isn't a syntax error...I tried it before I posted. In fact
>> def t(x) :
>>  def I(x) : return x
>>  return I
>>
>> is correct.
> 
> You've made the unfortunate mistake of indenting it with tabs, which do
> not show up on some newsreaders.  I see the tabs in Google; people
> using Microsoft Outlook do not.
> 
> Always use spaces when posting, and use them in your code as well.
> Spaces are the current recommended practice, and in the future tabs
> might become illegal.  I'd prefer tabs myself, but it's more important
> to respect community standards than to stick to some silly preference
> you have.
> 
> 
>> Decorators are a way to add "syntactic" sugar to Python,
>> extending it in ways that make it useful for tools. What
>> I am trying to do is lessen the impact on the time used
>> in executing Python code when I use some forms of decorators.
> 
> One suggestion.  Have you run the script, determined it's too slow, and
> are trying to optimize?  If not (and it doesn't sound like you are), I
> suggest that it's too soon to worry about whether this decorator has
> any overhead.  You may end up doing a lot of work optimizing that will
> ultimately have very little benefit.
> 
> Having said that, this decorator will not affect calling overhead at
> all.  The decorator is applied when the module is loaded, not when the
> decorated function is called.
> 
> 
> Carl Banks

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


If Statement Error (Tic Tac Toe)

2005-11-01 Thread ale . of . ginger
Greetings!  I am trying to make a multiplayer (no AI, 2 person) game of
tic tac toe in Python.  So far it has been pretty simple.  My only
concern is with the win checking to see if a person has won.  At first
it looked like it was working, but now it sometimes assigns a win when
you enter an X or O (doesn't matter) on certain tiles (row 1, column 1
won't be an error, but row 2, column 3 will be...).  If you can find
the problem, I'd be very thankful!  Here's the code:

# TIC TAC TOE
# Started: 10/31/05
# Ended:  still in progress

loop = 1

while loop == 1:
print "TIC TAC TOE"
print "1 - Play Multiplayer"
print "2 - Quit"
option = input("> ")

if option == 2:
# QUIT
loop = 0

if option == 1:
# MAIN GAME LOOP
print "Rules:  You will alternate turns."
print "On your turn, you can place your letter (O = Player 1 or
X = Player 2)",
print "in any unoccupied square."
print "The first to get 3 in a row wins.  Good luck!"

gameboard = [' ',' ',' ',' ',' ',' ',' ',' ',' ']

win = 0
turnnumber = 0

while win != 1:
if turnnumber % 2 == 0:
print " "
print "Player 1"
print " "
print
"[",gameboard[0],"]","[",gameboard[1],"]","[",gameboard[2],"]"
print
"[",gameboard[3],"]","[",gameboard[4],"]","[",gameboard[5],"]"
print
"[",gameboard[6],"]","[",gameboard[7],"]","[",gameboard[8],"]"
print "What row?"
row = input("> ")
print "What column?"
column = input("> ")

if (row > 3 or row < 1) or (column > 3 or column < 1):
print "Exceeeded limits."
turnnumber = turnnumber - 1

if row == 1 and column == 1:
if gameboard[0] != ('O' or 'X'):
gameboard[0] = ('O')
else:
print "This cell is already filled."
turnnumber = turnnumber - 1

if row == 2 and column == 1:
if gameboard[3] != ('O' or 'X'):
gameboard[3] = ('O')

else:
print "This cell is already filled."
turnnumber = turnnumber - 1
if row == 3 and column == 1:
if gameboard[6] != ('O' or 'X'):
gameboard[6] = ('O')
else:
print "This cell is already filled."
turnnumber = turnnumber - 1

if row == 1 and column == 2:
if gameboard[1] != ('O' or 'X'):
gameboard[1] = ('O')

else:
print "This cell is already filled."
turnnumber = turnnumber - 1

if row == 2 and column == 2:
if gameboard[4] != ('O' or 'X'):
gameboard[4] = ('O')
else:
print "This cell is already filled."
turnnumber = turnnumber - 1

if row == 3 and column == 2:
if gameboard[7] != ('O' or 'X'):
gameboard[7] = ('O')

else:
print "This cell is already filled."
turnnumber = turnnumber - 1

if row == 1 and column == 3:
if gameboard[2] != ('O' or 'X'):
gameboard[2] = ('O')

else:
print "This cell is already filled."
turnnumber = turnnumber - 1

if row == 2 and column == 3:
if gameboard[5] != ('O' or 'X'):
gameboard[5] = ('O')
else:
print "This cell is already filled."
turnnumber = turnnumber - 1

if row == 3 and column == 3:
if gameboard[8] != ('O' or 'X'):
gameboard[8] = ('O')

else:
print "This cell is already filled."
turnnumber = turnnumber - 1

turnnumber = turnnumber + 1

if (((gameboard[0] and gameboard[1] and gameboard[2]) ==
'O') or ((gameboard[3] and gameboard[4] and gameboard[5]) == 'O') or
((gameboard[6] and gameboard[7] and gameboard[8]) == 'O')\
or ((gameboard[0] and gameboard[3] and gameboard[6]) ==
'O') or ((gameboard[1] and gameboard[4] and gameboard[7]) == 'O') or
((gameboard[2] and gameboard[5] and gameboard[8]) == 'O')\
or ((gameboard[0] and gameboard[4] and gameboard[8]) ==
'O') or ((gameboard[2] and gameboard[4] and gameboard[6]) == 'O')):
print "Player 1 wins!"
w

Re: If Statement Error (Tic Tac Toe)

2005-11-01 Thread ale . of . ginger
Thank you.  It seems I didn't understand logic statements as much as I
thought I did!

The one remaining question I have deals with this:

if gameboard[cell] not in 'OX':
gameboard[cell] = 'O'
 else:
print "This cell is already filled."
turnnumber -= 1

(gameboard[cell] not in 'OX' is the gameboard[cell] != 'OX' text I sort
of used in my code, right?)

I am confused about "OX":  what exactly *is* it?  After that, I plan to
rewrite all the code... :)

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


Re: If Statement Error (Tic Tac Toe)

2005-11-01 Thread ale . of . ginger
So is there a way I have to set up the string OX in the beginning?  Is
this where it houses the location of the Xs and Os to determine whether
or not a letter is already there?

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


Re: If Statement Error (Tic Tac Toe)

2005-11-01 Thread ale . of . ginger
Nevermind my previous reply: I've been fixing up the code and
understand it.  I'm at a nifty 80 lines where I am at now rather than
209 lines in the previous version!  The changes are immense!

The only problem I have is whenever player two goes, it says the cell
is filled.  But the code:

if gameboard[cell] not in 'OX':
gameboard[cell] = 'X'
else:
print "This cell is already filled."
turnnumber = turnnumber - 1

is not any different than the code I am using for player one.  Anything
I have to change regarding 'OX' or something else?

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


Re: If Statement Error (Tic Tac Toe)

2005-11-02 Thread ale . of . ginger
The code's indentation was fine - I forgot to declare cell in player
two's section and not just in player one.

The code (including the win check, for once!) is working.  The last
obstacle is my tie checker; it doesn't seem to like what I have:

if ((gameboard[0:9] is 'X' or 'O') and (win == 0)):
 print "Tie."
 win = 2

Will the [0:9] range not work in this?  Should I write out each option?
 Or is there some way to check if all things in the list are NOT ' '?

I tried

if ((gameboard[0:9] is not ' '))

but it didn't like that - once again maybe the range is the culprit.
Hopefully this will be the last help I need, thanks once again.

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


Not Equal to Each Other?

2005-11-03 Thread ale . of . ginger
Another question:  I am writing a sudoku solving program.  The
'solving' part of is just multiple iterations.  It will take random
numbers and keep switching it all around until a set of logic
statements has been met (ie; all numbers in a row are not equal to each
other) ... that's where my question comes in.

Cellboard = my list for storing each row/column's data.

Rather than writing

cellboard[0] is not* (cellboard[1] and cellboard[2] and cellboard[3]
and cellboard[4] ... cellboard[8])
cellboard[1] is not (cellboard[0] and cellboard[2] and cellboard[3] and
cellboard[4] ... cellboard[8])
etc...

* should this be != ?

the above so that all the data in one row is not equal to each other,
is there something I can write to make it simpler?  For example,
(cellboard[0] is not cellboard[1] is not ... cellboard[8]) only worked
for the numbers to the left and right of the cell - is there anyway I
can expand this to cover all numbers in a set range?

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


Re: Not Equal to Each Other?

2005-11-03 Thread ale . of . ginger
For the

not cellboard[0] in cellboard[1:8] (I knew about ranges/slicing using a
colon, can't believe I didn't think of that!)

line, will I have to write that out for each number?

So the line:

not cellboard in ((cellboard[1:8]) and (cellboard[9] and cellboard[18]
and cellboard[27] and cellboard[36] and cellboard[45] and cellboard[54]
and cellboard[63] and cellboard[72]) and (cellboard[1:2] and
cellboard[9:11] and cellboard[18:20]))

will cover all the logic requirements for the number in cell 0 (well,
row 1, column 1).

But will I have to copy + paste + edit that for all 81 cells?  That
isn't complicated, just tedious - thanks though.

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


Re: Not Equal to Each Other?

2005-11-04 Thread ale . of . ginger
How do I 'define' set?  Is there something to include (like import
random)?

while (choice == 3) and len(set(cellboard[0:8]))==len(cellboard[0:8]):
# DEFINE TWO RANDOM VARIABLES (ONE FOR ARRAY, ONE FOR NUMBER
VALUE)
solvingrandom = random.randint(1,9)
cellboardrandom = random.randint(0,8)
set(cellboard[0:8])

# CHECK TO MAKE SURE THE RANDOMLY ASSIGNED CELL DOES NOT HAVE A
VALUE
if (cellboard[cellboardrandom] is not ('1' or '2' or '3' or '4'
or '5' or '6' or '7' or '8' or '9')):
cellboard[cellboardrandom] = solvingrandom

The above is my code (right now it will only work for the first row's
numbers).  Anything else I need to add?

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


Goto XY

2005-11-08 Thread ale . of . ginger
Is there some command in python so that I can read a key's input and
then use a gotoxy() function to move the cursor on screen?  e.g.:
(psuedo-code)

When the right arrow is pushed, cursor gotoxy(x+1,y)

Thanks.

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


Re: Goto XY

2005-11-08 Thread ale . of . ginger
Thanks -- I downloaded WConio.

When I just tried it out in the IDLE, it said:

NameError: name 'WConio' is not defined

I assume I have to use a header somewhere (import WConio ?).  Or is
there something I'm missing (I downloaded the Python 2.4 (I have 2.4.2)
auto installer and it ran fine...)

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


Re: Goto XY

2005-11-09 Thread ale . of . ginger
OK - I added the import WConio line.  But when I run

import WConio
print "going to x10,y10..."
WConio.gotoxy(10,10)
print "Done"

the above, I get the following error:

WConio.gotoxy(10,10)
error: GetConOut Failed

I installed the WConio to the ../site-packages/ folder in Python24, and
when it didn't work I also moved the files in there to the /Lib/ folder
where other things are like random, but that didn't seem to work either.

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


Curses & Keypress

2005-11-10 Thread ale . of . ginger
Now that I have gotoxy() down for moving the cursor around, I want that
to be a result of keypresses (namely from the numpad -- 7 = NorthWest,
8 = North, 9 = NE, etc...).  I have little clue how to do this.  After
searching google, I've come upon this; include:

import curses

in the header.  However, I've found various methods of actually reading
the keyboard press (getch(), raw_input, etc.).  What is the best method
to use for reading keypress, so I can have something like:

if (keypressvariable == 'numpad7'):
 WConio.gotoxy(x-1,y+1)

etc...

Thanks.

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