Re: [Tutor] Re: Data storage, SQL?

2005-02-13 Thread Kent Johnson
Liam Clarke wrote:
...So,  trying to get this straight - if I were going to use SQLite,
what would I actually download from http://www.sqlite.org/sqlite.html
?
SQLite itself does not use / interface with Python. So you would download the appropriate version of 
SQLite for your platform from http://www.sqlite.org/download.html. Then get the matching release of 
pysqlite from http://sourceforge.net/projects/pysqlite/ - this is the Python interface to SQLite.

Also, would Gadfly be easier, being native Python?
Gadfly might be a little easier to install since there is only one piece. Both Gadfly and SQLite 
have DB-API compliant drivers and use SQL for their command language, so in use they will be 
similar. Gadfly keeps the database in memory so for large amounts of data it won't work. I think 
SQLite has been around longer than Gadfly so it may be more mature.

If you want a simple database with a Pythonic interface, take a look at KirbyBase. Though from your 
brief description I think you will want a database that supports joins.

There is a great variety of databases usable from Python. Most of them use DB-API and SQL for the 
interface, so you have to pick one based on features. I guess I see three rough categories.


This is a rough opinion based on reading about these databases. My own experience is with MS SQL 
Server, PostgreSQL and MS Access.


At the top of the heap are the industrial strength databases. This includes free products like 
MySQL, PostgreSQL and Firebird as well as commercial products like MS SQL Server, Sybase and Oracle. 
These databases will take anything you can throw at them with style and aplomb. (MySQL is probably 
the most limited of this category but it is widely used and clearly quite capable.) They are well 
supported with tools and they are used in a wide variety of projects.

In the middle tier are databases that are not as full featured but still very usable for small to 
midsize work. I would put SQLite and Gadfly into this category. Some people would argue that MySQL 
belongs here. These databases will be missing features like transactions, large database support, 
unicode support...

In the bottom tier are programs that are more of a persistence mechanism than a true database. I put 
KirbyBase here along with the standard Python shelve and dbm modules.

OK...I don't know if this has been any help...I suggest you look at the *features* of SQLite and 
Gadfly and see if either is missing anything you need.

Finally, you might want to look at SQLObject. This is a wrapper on top of the database that makes 
your objects persist themselves. It shields you from DB-API and SQL. http://sqlobject.org

HTH,
Kent
Regards, 

Liam Clarke
On Sat, 12 Feb 2005 14:27:21 +0500, Sandip Bhattacharya
<[EMAIL PROTECTED]> wrote:
On Fri, 11 Feb 2005 20:09:10 +1300, Liam Clarke wrote:

Hi,
I'm looking to create a prog that will store disparate bits of info
all linked together, i.e. address details for a person, transaction
records, specific themes, and the ability to search by certain
criteria, so I'm pretty sure I want a database.
Can anyone recommend a useful database library for Python that's not
too complex?
Also, I keep hearing about SQL, would this be the best way to go? I
don't know much about databases.
You can take a look at sqlite
(http://www.sqlite.org/). It doesn't require a client
server setup, and offers you the same sql syntax for manipulating data on
it.
Some amazing facts about this from the website:
[...]
SQLite is a small C library that implements a self-contained,
embeddable, zero-configuration SQL database engine. Features include:
* Transactions are atomic, consistent, isolated, and durable  (ACID)
   even after system crashes and power failures.
* Zero-configuration - no setup or administration needed.
* Implements most of SQL92.
* A complete database is stored in a single disk file.
* Database files can be freely shared between machines with
 different byte orders.
* Supports databases up to 2 terabytes (2^41 bytes) in size.
* Sizes of strings and BLOBs limited only by available memory.
* Small code footprint: less than 30K lines of C code, less
   than 250KB code space (gcc on i486)
* Faster than popular  client/server database engines
 for most common operations.
* Simple, easy to use API.
* Well-commented source code with over 95% test coverage.
* Self-contained: no external dependencies.
* Sources are in the public domain. Use for any purpose.
The SQLite distribution comes with a standalone command-line access
program (sqlite) that can be used to administer an SQLite database and
which serves as an example of how to use the SQLite library.
[...]
- Sandip
--
Sandip Bhattacharya*Puroga Technologies   * [EMAIL PROTECTED]
Work: http://www.puroga.com   *Home/Blog: http://www.sandipb.net/blog
PGP/GPG Signature: 51A4 6C57 4BC6 8C82 6A65 AE78 B1A1 2280 A129 0FF3
___
Tutor maillist  -  Tutor@python.org
http://mail.pyt

Re: [Tutor] Re: Accessing local variables from nested functions.

2005-02-13 Thread Karl Pflästerer
On 13 Feb 2005, [EMAIL PROTECTED] wrote:

>
> Karl Pflästerer wrote on Sun, 13 Feb 2005 12:15:03 +0100:
>
>> what's the Python way of accessing local variables in nesting functions? For 

I didn't wrote that; please quote correctly.  Thanks.



   Karl
-- 
Please do *not* send copies of replies to me.
I read the list
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Re: Accessing local variables from nested functions.

2005-02-13 Thread Andrei
Karl Pflästerer wrote on Sun, 13 Feb 2005 12:15:03 +0100:

> what's the Python way of accessing local variables in nesting functions? For 

> then there's no problem in running such function, but what if I'd like to 
> modify var1 so that the change were vissible in p()?

I'd use return in the form of

def p():
v = 3
def q():
return v+1
v = q()

If you need to modify a lot of p-vars inside q, I'd say it's probably wiser
to go with a class and appropriate methods.

-- 
Yours,

Andrei

=
Real contact info (decode with rot13):
[EMAIL PROTECTED] Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V ernq
gur yvfg, fb gurer'f ab arrq gb PP.

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Re: Data storage, SQL?

2005-02-13 Thread Liam Clarke
...So,  trying to get this straight - if I were going to use SQLite,
what would I actually download from http://www.sqlite.org/sqlite.html
?

Also, would Gadfly be easier, being native Python?

Regards, 

Liam Clarke


On Sat, 12 Feb 2005 14:27:21 +0500, Sandip Bhattacharya
<[EMAIL PROTECTED]> wrote:
> On Fri, 11 Feb 2005 20:09:10 +1300, Liam Clarke wrote:
> 
> > Hi,
> >
> > I'm looking to create a prog that will store disparate bits of info
> > all linked together, i.e. address details for a person, transaction
> > records, specific themes, and the ability to search by certain
> > criteria, so I'm pretty sure I want a database.
> >
> > Can anyone recommend a useful database library for Python that's not
> > too complex?
> > Also, I keep hearing about SQL, would this be the best way to go? I
> > don't know much about databases.
> 
> You can take a look at sqlite
> (http://www.sqlite.org/). It doesn't require a client
> server setup, and offers you the same sql syntax for manipulating data on
> it.
> 
> Some amazing facts about this from the website:
> 
> [...]
> SQLite is a small C library that implements a self-contained,
> embeddable, zero-configuration SQL database engine. Features include:
> 
> * Transactions are atomic, consistent, isolated, and durable  (ACID)
> even after system crashes and power failures.
> * Zero-configuration - no setup or administration needed.
> * Implements most of SQL92.
> * A complete database is stored in a single disk file.
> * Database files can be freely shared between machines with
>   different byte orders.
> * Supports databases up to 2 terabytes (2^41 bytes) in size.
> * Sizes of strings and BLOBs limited only by available memory.
> * Small code footprint: less than 30K lines of C code, less
> than 250KB code space (gcc on i486)
> * Faster than popular  client/server database engines
>   for most common operations.
> * Simple, easy to use API.
> * Well-commented source code with over 95% test coverage.
> * Self-contained: no external dependencies.
> * Sources are in the public domain. Use for any purpose.
> 
> The SQLite distribution comes with a standalone command-line access
> program (sqlite) that can be used to administer an SQLite database and
> which serves as an example of how to use the SQLite library.
> 
> [...]
> 
> - Sandip
> 
> --
> Sandip Bhattacharya*Puroga Technologies   * [EMAIL PROTECTED]
> Work: http://www.puroga.com   *Home/Blog: http://www.sandipb.net/blog
> 
> PGP/GPG Signature: 51A4 6C57 4BC6 8C82 6A65 AE78 B1A1 2280 A129 0FF3
> 
> 
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 


-- 
'There is only one basic human right, and that is to do as you damn well please.
And with it comes the only basic human duty, to take the consequences.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Re: References in loops

2005-02-12 Thread Brian Beck
Andrei wrote:
Numbers are immutable, so the element 1 can't change into a 2 inside the 
list. If 1 was not immutable, e.g. a list you could modify it and then 
it would be "updated" in the original list too.
It doesn't have anything to do with mutability, only the scope of i. 
Consider a list of lists (lists are mutable):

py> l = [[1], [2], [3]]
py> for i in l:
i = [0]
py> print l
[[1], [2], [3]]
Notice that even though each i (list) is mutable, rebinding the name i 
in the loop has no effect on the list.

I tend to use list comprehensions for this:
aList = [elem+1 for elem in aList]
This is probably the best solution, provided that the operation you want 
to perform on each element is simple enough to fit in an expression. 
Even then, just put the operation into a function.

--
Brian Beck
Adventurer
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Re: Data storage, SQL?

2005-02-12 Thread Sandip Bhattacharya
On Fri, 11 Feb 2005 20:09:10 +1300, Liam Clarke wrote:

> Hi, 
> 
> I'm looking to create a prog that will store disparate bits of info
> all linked together, i.e. address details for a person, transaction
> records, specific themes, and the ability to search by certain
> criteria, so I'm pretty sure I want a database.
> 
> Can anyone recommend a useful database library for Python that's not
> too complex?
> Also, I keep hearing about SQL, would this be the best way to go? I
> don't know much about databases.

You can take a look at sqlite
(http://www.sqlite.org/). It doesn't require a client
server setup, and offers you the same sql syntax for manipulating data on
it.

Some amazing facts about this from the website:

[...]
SQLite is a small C library that implements a self-contained,  
embeddable, zero-configuration SQL database engine. Features include:

* Transactions are atomic, consistent, isolated, and durable  (ACID)
even after system crashes and power failures. 
* Zero-configuration - no setup or administration needed. 
* Implements most of SQL92.
* A complete database is stored in a single disk file. 
* Database files can be freely shared between machines with 
  different byte orders. 
* Supports databases up to 2 terabytes (2^41 bytes) in size. 
* Sizes of strings and BLOBs limited only by available memory. 
* Small code footprint: less than 30K lines of C code, less
than 250KB code space (gcc on i486) 
* Faster than popular  client/server database engines 
  for most common operations. 
* Simple, easy to use API.
* Well-commented source code with over 95% test coverage.
* Self-contained: no external dependencies. 
* Sources are in the public domain. Use for any purpose.

The SQLite distribution comes with a standalone command-line access
program (sqlite) that can be used to administer an SQLite database and
which serves as an example of how to use the SQLite library. 

[...]

- Sandip

-- 
Sandip Bhattacharya*Puroga Technologies   * [EMAIL PROTECTED]
Work: http://www.puroga.com   *Home/Blog: http://www.sandipb.net/blog

PGP/GPG Signature: 51A4 6C57 4BC6 8C82 6A65 AE78 B1A1 2280 A129 0FF3



___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Re: References in loops

2005-02-12 Thread Andrei
Matt Dimmic wrote:
In Python, one bug that often bites me is this:
(example A)
aList = [1,2,3]
for i in aList:
i += 1
print aList
--> [1,2,3]
Numbers are immutable, so the element 1 can't change into a 2 inside the 
list. If 1 was not immutable, e.g. a list you could modify it and then 
it would be "updated" in the original list too.

This goes against my intuition, which is that aList == [2,3,4], probably
because so much in Python is passed by reference and not by value. Of
course I can always use range() or enumerate():
I tend to use list comprehensions for this:
aList = [elem+1 for elem in aList]
but it's barely shorter than the explicit loop, so not necessarily an 
improvement from that point of view. But at least it prevents the bug 
from biting :).

Yours,
Andrei
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Re: Larger program organization

2005-02-12 Thread Javier Ruere
Ryan Davis wrote:
> I'm starting to make a code-generation suite in python, customized to
> the way we ASP.NET at my company, and I'm having some trouble finding a
> good way to organize all the code.  I keep writing it, but it feels more
> and more spaghetti-ish every day.
> 
> I'm going to look at the other stuff in site-packages to see if I can
> glean any wisdom, and have googled a bit, coming up mostly blank or with
> trivial examples.  Are there any helpful links or advice anyone has for
> building larger systems? 
> 
> My background is mostly C#, so I'm used to the ridiculous rigidity of
> strongly-typed languages. I have been using python for helper apps for a
> few months now, so am pretty familiar with the syntax now, but I don't
> know any of the patterns yet.  My nefarious goal is to supplant
> C#/ASP.NET with Python, but I need to figure out how to make programs
> clients want to pay for before I can make any reasonable argument.

  I have worked with C# + ASP.NET and liked it very much. It felt more
similar to Python than Java; and ASP.NET rules! :)
  WRT your original question: Organize the code as you would in a C#
project unless it feels unnatural. Sorry about that last condition but
it's the best I can do[1]. :) Get Bicycle Repair Man[2] or another
refactoring browser and hack away!

Javier

[1] Some usefull links:
http://dirtsimple.org/2005/01/courage-to-do-things-simply.html
http://dirtsimple.org/2004/12/python-is-not-java.html
http://dirtsimple.org/2004/12/java-is-not-python-either.html

[2] http://bicyclerepair.sourceforge.net/

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Re: Might be a silly question!

2005-02-12 Thread Liam Clarke
I suppose, you could do it like this  - 

gamma = 5,

and access with gamma[0]. But, there'd be nothing to stop you reassigning gamma.

On Fri, 11 Feb 2005 18:44:18 -, Alan Gauld <[EMAIL PROTECTED]> wrote:
> > I have been reading code written before me (mind you it's C++) and
> the
> > authors seemed to follow what ever style they wished to that day.
> 
> And that's C++ style, it has no single standard approach...
> 
> > that's the nature of the beast.
> 
> How very true.
> 
> Alan G.
> 
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 


-- 
'There is only one basic human right, and that is to do as you damn well please.
And with it comes the only basic human duty, to take the consequences.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Re: Negative IF conditions

2005-02-11 Thread Andrei
Mark Brown wrote:
I'm a newbie and was wondering which of these IF conditions is better 
structure:

   1. if not os.path.exists('filename'):
   2. if os.path.exists('filename') == False:
I prefer the "if not" variety.
Yours,
Andrei
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Re: Might be a silly question!

2005-02-11 Thread Alan Gauld
> I have been reading code written before me (mind you it's C++) and
the
> authors seemed to follow what ever style they wished to that day.

And that's C++ style, it has no single standard approach...

> that's the nature of the beast.

How very true.

Alan G.

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Re: Might be a silly question!

2005-02-11 Thread Jeffrey Maitland
Thanks that's what I thought. 

Wasn't 100% sure that is what prompted me to ask the question in here. 

As for the CAPS thing for constants, I generally try and practice (to the 
best of my knowledge) proper programming consepts/styles/standards. However 
I have been reading code written before me (mind you it's C++) and the 
authors seemed to follow what ever style they wished to that day.  Oh well 
that's the nature of the beast. 

Thanks again for clearing that up for me. 

Jeff 

Bill Mill writes: 

Jeff, 

On Fri, 11 Feb 2005 10:03:30 -0500, Jeffrey Maitland <[EMAIL PROTECTED]> wrote:
Hello all, 

I am drawing a blank right now and can't seem to find anything on it and I
am sure this issue has been addressed before, so here is the question. 

Can and if you can how do you set a variable as a constant? 

Example of what I mean: (this is loose and not python since variable type
declaration is not needed in python) 

CONST int gamma = 5 

This would mean in my little mind that the variable gamma which is an
integer of 5 can not be changed in the code and would throw an error if you
tried. Just wondering if there is a way of doing this in Python.
There is no real way to guarantee this in Python. 

 This is
just to clear this up in my mind it means nothing to my code since the way I
write variable names any variable I want to remain unchanged I use caps to
help distinguish easily.
Constants are enforced by convention in Python. Any variable with a
name in ALL CAPS is considered to be a constant, and it is considered
bad programming style to change it. While it sounds like a weak
system, and I'm sure there have been problems with it, I've never
heard of one. Remember to only import the names you need from the
classes you import, and you should be fine. 

Peace
Bill Mill
bill.mill at gmail.com

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


RE: [Tutor] Re: Perl Symbology

2005-02-10 Thread Smith, Jeff
Abel,

No, you don't have to escape them all.  Perl treats single and double
quotes differently.  Single-quoted strings don't do interpolation and
double-quoted strings do.  

Jeff

-Original Message-
From: Abel Daniel [mailto:[EMAIL PROTECTED] 
Sent: Thursday, February 10, 2005 12:23 PM
To: tutor@python.org
Subject: [Tutor] Re: Perl Symbology


Bill Mill writes:

> I get the impression that many pythonistas don't like string  
>interpolation. I've never seen a clear definition of why. From "import 
>this":

 Explicit is better than implicit.

And doesn't perl's method mean that you have to escape _every_ _single_
'$' in strings? I think having to escape '\' is bad enough.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Re: Perl Symbology

2005-02-10 Thread Bill Mill
On Thu, 10 Feb 2005 18:22:30 +0100, Abel Daniel <[EMAIL PROTECTED]> wrote:
> Bill Mill writes:
> 
> > I get the impression that many pythonistas don't like string
> > interpolation. I've never seen a clear definition of why.
> >From "import this":
> 
>  Explicit is better than implicit.
> 
> And doesn't perl's method mean that you have to escape _every_
> _single_ '$' in strings? I think having to escape '\' is bad enough.

Abel,

You've provided me with what is approximately the eleventy-seventh
explanation I've gotten as to why string interpolation is bad. I don't
think that any of them are "stupid", per se, but neither do I think
that any of them are strong enough to be convincing. In my perfect
language, string interpolation would be on by default.

That said, there are enough reasons to think that it's a bad idea that
it is warranted to avoid turning it on by default. I don't mind typing
pp("interpolate $mystring"), and although I do wish python
standardized it before version 2.4 [1], I hardly even feel that it's a
wart in the language.

I just wanted to tell the person who wanted string interpolation that
it's easy to add into the language and easy to use. One should not
take python out of consideration if one feels that string
interpolation is a killer feature.

Peace
Bill Mill
bill.mill at gmail.com

[1] http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/335308
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: ****SPAM(10.2)**** [Tutor] Re: python's default argument value handling in functions - weird syntax? problem grappling with the concept

2005-02-10 Thread Bob Gailer
I regret my original answer since it led to frustration. I missed the point 
that the local variable is pointed to the once-created default object, and 
that reassigning to that name does NOT affect the once-created default object.

I am glad for a community in which we can cover each other's blind spots.
Bob Gailer
mailto:[EMAIL PROTECTED]
303 442 2625 home
720 938 2625 cell 

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Re: Perl Symbology

2005-02-10 Thread Abel Daniel
Bill Mill writes:

> I get the impression that many pythonistas don't like string
> interpolation. I've never seen a clear definition of why.
>From "import this":

 Explicit is better than implicit.

And doesn't perl's method mean that you have to escape _every_
_single_ '$' in strings? I think having to escape '\' is bad enough.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Re: python's default argument value handling in functions - weird syntax? problem grappling with the concept

2005-02-09 Thread Jeffrey Lim
On Wed, 09 Feb 2005 23:50:49 +0100, Abel Daniel <[EMAIL PROTECTED]> wrote:
> 
> quoted lines are from Jeffrey Lim
> [... I have rearranged the order of the quotes ...]
> 

thanks, Abel! Especially for the part on the 'C' concept of variables,
vs that of Python's (and the links, as well).

appreciated it, and thanks, all, for such a great "first-time tutor
list experience" already,
-jf
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Re: python's default argument value handling in functions - weird syntax? problem grappling with the concept

2005-02-09 Thread Abel Daniel

quoted lines are from Jeffrey Lim
[... I have rearranged the order of the quotes ...]

> How is 'L == None' even possible all the time, given that for
> def f(a, L=[]):
> L.append(a)
> return L
> , L isn't even [] except for the first call to 'f'?

This is the important point. You see, its true that L != [] for those
calls, but despite this, L _is_ []. I guess this sounds wierd, so I'll
clarify it:

Lets try it with a little modification. Instead of "def f(a, L=[])",
we will use "def f(a, L=l)", where l is an empty list. This surely
shouldn't cause any difference, should it?

>>> l=[]
>>> def f(a, L=l):
... L.append(a)
... return L
... 
>>> f(1)
[1]
>>> f(2)
[1, 2]
>>> f(3)
[1, 2, 3]

So far, so good. Now lets see whether L is [] or not:

>>> a=f(4) # so now a is whatever L was inside the function
>>> a == l
True

and:

>>> a is l  
True

So L _is_ [], isn't it? How can this happen? After all, by now L is
[1,2,3,4], right? And l is an empty list, right? Well, wrong:

>>> l
[1, 2, 3, 4]

So the strange thing is that even though L is _not_ [] (as in, its not
an empty list) it _is_ [] in some sence. That is, it is the _same_
list which was [] once. This second sentence might sound pretty
wierd. You have to keep in mind, that every time you type [], python
will create a _new_, empty list. This means that:

>>> [] is []
False

The big difference between the "def f(a, L=[])" and "def f(a, L=None)"
cases is that in the first, L is a list, and lists are mutable. In the
second, L is None and obviously, None is not mutable. In both cases
you give an object as a default value. In both cases, L will _allways_
be this object at the first line of the function when you call the
function. The difference is that in the first case, although you can't
change the _identity_ of the default value, you can change its
_content_ . And thats what you do with the line "L.append(a)".

Keep in mind that L=[] does _not_ copy the list. In fact, in python
even a=5 does not copy anything. In C, variables might be thought of
as little drawers that have something in them. When you say a=b, the
contents of b get copied to a. In python, however, variables are
better thought of as labels. When you say a=5, you put a label on the
number 5 object. Its like saying "I want to be able to call that
number a". When doing a=b, there is no copying, what happens is that
the label 'a' gets moved to the object which has the label 'b' on it.

In the previous paragraph, I have written "when you say a=5, you put a
label on the number 5 object". Maybe I should have written "you put a
label on a number 5 object". Notice the difference? For numbers, one
could claim that there is no difference. After all, there is only one
number 5, right? However, as we have seen above, for lists, you can't
claim the same. There is no _the_ []. Every '[]' will create a new
one.

If you think of variables as labels on objects, and objects as having
content and identity, everything should become clear. ('==' compares
by value, that is, by content, 'is' compares by identity. Make sure
not to mix identity with eguality.)

Recommended reading:

http://www.effbot.org/zone/python-objects.htm (understanding python
objects, pretty short)

http://starship.python.net/crew/mwh/hacks/objectthink.html ("variables
as labels", a bit longer)



ps. For extra wierdness, in python "there is only one number 5" isn't
true for large numbers:
>>> a=100
>>> b=100
>>> a is b
False

Using a large number is important: integers up to 99 are cached, so
they _are_ unique (we would get True above). For larger numbers, the
cacheing is more subtle, for example:
>>> a, b = 100, 100
>>> a is b
True

--
Abel Daniel
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Re: print out lines that start with a word

2005-02-09 Thread Wolfram Kraus
Liam Clarke wrote:
print [w for w in j.split() if w[0] == '*' and w[-1] == '*'] 

Wouldn't that only work if it was bug *car* jeff?
I can imagine bug*car*jeff would throw it.
Cheers, 

Liam Clarke
x = 'bug*car*jeff*foo*bar'
[x.split('*')[a] for a in range(1,len(x.split('*')), 2)]
When you mix * and spaces I will give up ;-)!
Wolfram
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Re: print out lines that start with a word

2005-02-09 Thread Liam Clarke
print [w for w in j.split() if w[0] == '*' and w[-1] == '*'] 


Wouldn't that only work if it was bug *car* jeff?

I can imagine bug*car*jeff would throw it.

Cheers, 

Liam Clarke
-- 
'There is only one basic human right, and that is to do as you damn well please.
And with it comes the only basic human duty, to take the consequences.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Re: print out lines that start with a word

2005-02-09 Thread Wolfram Kraus
Damn!
C&P-bug here to! Is this a virus? ;-)
print [w for w in j.split() if words[0] == '*' and words[-1] == '*']
Should be:
print [w for w in j.split() if w[0] == '*' and w[-1] == '*']
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Re: print out lines that start with a word

2005-02-09 Thread Wolfram Kraus
Liam Clarke wrote:
x= ["Dude", 'How is it going man', ' ']
print x
['Dude', 'How is it going man', ' ']

j=[]
for item in x:
... if re.search('\S+',item):
... j.append(item)

print j
['Dude', 'How is it going man']
What about:
x= ["Dude", 'How is it going man', ' ']
print [a for a in x if a.strip()]

Now, I first did that in a Perl script, but it easily comes across to
Python. \S+ will usually mean 'one or more non-whitespace characters'.
Brilliant for when your first Perl script accidentally appended \n to
everything, even \n and \t. *embarassed*
Whereas, while I'm sure there is a string method that can do that, I'm
not sure what it is.
Well the documentation on that is not sooo big ;-)
Also - say you have a list of words - 
j = " bag apple tomato cheese *marmite*  sausages *scones*"

and you wanted to pick up each word that was asterisked. 
I did this as a string method then a regex.


try:
... 	indexes=[]
... 	lastIndex = 0
... 	while 1:
... 		x = j.index("*", lastIndex + 1)
... 		indexes.append(x)
... 		lastIndex = x
... except ValueError:
... 	pass
... 

print indexes
[4,  10]
myString = j[5:10]

That gives me  [25, 33, 45, 52], propably a C&P bug?
Now the regular expression - 


x = re.finditer("\*(?P.*?)\*", j)
a = x.next()
print a.group('myString')
apple
Same error as above? And you said you want _all_ asteriksed words!
How about this cute lil list comprehension:
print [w for w in j.split() if words[0] == '*' and words[-1] == '*']
Now, while the regEx syntax is a big harsh to begin with, once you get
the hang of it, it's OK, and the string method version I used felt too
'hacky' for me. Of course, both only work with pairs of asterisks, so
I guess that makes them both hacky. : )
That's my 2c, I use string methods for stuff like that .startswith, .endswith, 
if 'foo' in x stuff is good as well. But sometimes, a regex is the
right tool for the job.
I didn't say that they are useless (and don't wanna troll or start a 
flameware), but IMHO they are a PITA when it comes to debugging. Ever 
touched a regexp after one year ;-)?

Regards, 

Liam Clarke
Greetings,
Wolfram
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Re: print out lines that start with a word

2005-02-09 Thread Liam Clarke
>>> x= ["Dude", 'How is it going man', ' ']
>>> print x
['Dude', 'How is it going man', ' ']

>>> j=[]
>>> for item in x:
... if re.search('\S+',item):
... j.append(item)

>>> print j
['Dude', 'How is it going man']

Now, I first did that in a Perl script, but it easily comes across to
Python. \S+ will usually mean 'one or more non-whitespace characters'.
Brilliant for when your first Perl script accidentally appended \n to
everything, even \n and \t. *embarassed*

Whereas, while I'm sure there is a string method that can do that, I'm
not sure what it is.

Also - say you have a list of words - 
j = " bag apple tomato cheese *marmite*  sausages *scones*"

and you wanted to pick up each word that was asterisked. 
I did this as a string method then a regex.


>>> try:
... indexes=[]
... lastIndex = 0
... while 1:
... x = j.index("*", lastIndex + 1)
... indexes.append(x)
... lastIndex = x
... except ValueError:
... pass
... 
>>> print indexes
[4,  10]
>>>myString = j[5:10]

Now the regular expression - 

>>> x = re.finditer("\*(?P.*?)\*", j)
>>> a = x.next()
>>> print a.group('myString')
apple

Now, while the regEx syntax is a big harsh to begin with, once you get
the hang of it, it's OK, and the string method version I used felt too
'hacky' for me. Of course, both only work with pairs of asterisks, so
I guess that makes them both hacky. : )

That's my 2c, I use string methods for stuff like that .startswith, .endswith, 
if 'foo' in x stuff is good as well. But sometimes, a regex is the
right tool for the job.


Regards, 


Liam Clarke

PS Pierre, my wife asked if you could write something in French so
that she could try and read it, as she's trying to pick up her French
again. If you don't mind.

On Wed, 09 Feb 2005 09:44:15 +0100, Pierre Barbier de Reuille
<[EMAIL PROTECTED]> wrote:
> Wolfram Kraus a écrit :
> > Liam Clarke wrote:
> >
> >> regexes are common across a lot of languages, even Java has them.
> >> Though the pain that would be I daren't not imagine. So the syntax is
> >>  familiar, whereas string methods may not be.
> >
> > But IMHO string methods are (more) explicit and readable, the name tells
> > you what the method is doing. I know that sometimes regexp are really
> > fine, e.g. extracting something from html or maybe speed issues (can
> > anyone enlighten me on that one?), but for simple task like the OP's
> > problem I'd always use string methods.
> >
> > Wolfram
> 
> I completely agree ! Then, it will very probably be more efficient. And
> the methods (or functions) like "startwith" are avalaible in almost
> every string library !
> 
> Pierre
> 
> --
> Pierre Barbier de Reuille
> 
> INRA - UMR Cirad/Inra/Cnrs/Univ.MontpellierII AMAP
> Botanique et Bio-informatique de l'Architecture des Plantes
> TA40/PSII, Boulevard de la Lironde
> 34398 MONTPELLIER CEDEX 5, France
> 
> tel   : (33) 4 67 61 65 77fax   : (33) 4 67 61 56 68
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 


-- 
'There is only one basic human right, and that is to do as you damn well please.
And with it comes the only basic human duty, to take the consequences.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Re: print out lines that start with a word

2005-02-09 Thread Pierre Barbier de Reuille
Wolfram Kraus a écrit :
Liam Clarke wrote:
regexes are common across a lot of languages, even Java has them. 
Though the pain that would be I daren't not imagine. So the syntax is
 familiar, whereas string methods may not be.
But IMHO string methods are (more) explicit and readable, the name tells 
you what the method is doing. I know that sometimes regexp are really 
fine, e.g. extracting something from html or maybe speed issues (can 
anyone enlighten me on that one?), but for simple task like the OP's 
problem I'd always use string methods.

Wolfram
I completely agree ! Then, it will very probably be more efficient. And 
the methods (or functions) like "startwith" are avalaible in almost 
every string library !

Pierre
--
Pierre Barbier de Reuille
INRA - UMR Cirad/Inra/Cnrs/Univ.MontpellierII AMAP
Botanique et Bio-informatique de l'Architecture des Plantes
TA40/PSII, Boulevard de la Lironde
34398 MONTPELLIER CEDEX 5, France
tel   : (33) 4 67 61 65 77fax   : (33) 4 67 61 56 68
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Re: print out lines that start with a word

2005-02-09 Thread Wolfram Kraus
Liam Clarke wrote:
regexes are common across a lot of languages, even Java has them. 
Though the pain that would be I daren't not imagine. So the syntax is
 familiar, whereas string methods may not be.
But IMHO string methods are (more) explicit and readable, the name tells 
you what the method is doing. I know that sometimes regexp are really 
fine, e.g. extracting something from html or maybe speed issues (can 
anyone enlighten me on that one?), but for simple task like the OP's 
problem I'd always use string methods.

Wolfram
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Re: print out lines that start with a word

2005-02-09 Thread Liam Clarke
regexes are common across a lot of languages, even Java has them.
Though the pain that would be I daren't not imagine. So the syntax is
familiar, whereas string methods may not be.


On Wed, 09 Feb 2005 09:00:52 +0100, Wolfram Kraus
<[EMAIL PROTECTED]> wrote:
> Ron Nixon wrote:
> > Can anyone tell me what I've done wrong in this
> > script.
> >
> > I'm trying to get only the lines that start with
> > "This" for a text file.
> >
> > Here's what I wrote:
> >
> >
> import re
> f = open('c:/lines.txt').readlines()
> for line in f:
> >
> >   match = re.search('^This',f)
> >   if line == match:
> >   print match
> >
> >
> Pardon my ignorance, but why is everybody fond of regexps ;-) ? Are they
> faster? What about good ol' startswith():
> http://docs.python.org/lib/string-methods.html#l2h-204
> Untested:
> 
> f = open('c:/lines.txt').readlines()
> for line in f:
>if line.startswith('This'):
>  print line # Or whatever match is, no regexp-expert here, sorry
> 
> Wondering,
> Wolfram
> 
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 


-- 
'There is only one basic human right, and that is to do as you damn well please.
And with it comes the only basic human duty, to take the consequences.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Re: print out lines that start with a word

2005-02-09 Thread Wolfram Kraus
Ron Nixon wrote:
Can anyone tell me what I've done wrong in this
script.
I'm trying to get only the lines that start with
"This" for a text file.
Here's what I wrote:

import re
f = open('c:/lines.txt').readlines()
for line in f:
match = re.search('^This',f)
if line == match:
print match

Pardon my ignorance, but why is everybody fond of regexps ;-) ? Are they 
faster? What about good ol' startswith(): 
http://docs.python.org/lib/string-methods.html#l2h-204
Untested:

f = open('c:/lines.txt').readlines()
for line in f:
  if line.startswith('This'):
print line # Or whatever match is, no regexp-expert here, sorry
Wondering,
Wolfram
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Re: manipulating a file

2005-02-08 Thread Danny Yoo


> >>This simplifies the code down to:
> >>
> >>###
> >>srcfile = open('/var/log/httpd-access.log.bak', 'r')
> >>dstfile = open('/var/log/httpd-access.log', 'w')
> >>for line in srcfile:
> >>if len(line) < 2086:
> >>dstfile.write(line)
> >>srcfile.close()
> >>dstfile.close()
> >>###
> >>
> >>
> I am actually mv log to bak and write the non offening entries back to
> log.


Hi Reed,

Oh, so the web server is still continuing to write things onto the open
log file then.  Out of curiosity, what web server are you using?

One remote possiblility for the weirdness might depend on how your web
server writes new log messages into the file: perhaps it can automatically
detect log file rotation, and may be overwriting http-access.log?  It's
very hard to say.  I'll talk about this a little more below.


> I can not be working on log as it needs to be able to accept new entries
> as the webserver is accessed.  Plus I am learning python, I could have
> sh scripted it easy but am broadening my horizons...

Sure, I think that's perfectly fine.  I think there was some confusion on
the list earlier, so I'm glad you cleared that up.


I'm still trying to figure out what could be causing the problem.  You
mentioned that you were running the programs as root, so permission
problems are probably not an issue.  I don't think we have enough
information to debug this, and I hate shooting arrows in random
directions.

I feel a little nervous programs that try to do 'in-place' changes.
Conceptually, we're trying to swap out httpd_access out from underneath
the httpd process's nose, and that might not work.  If you're doing a
'mv', then the log messages should continue to log to the backup file, if
I understand how apache works.

Let's test something.  Can you try writing the truncated log to another
file, like '/var/log/http-access.truncated.log'?  This at least should
prevent any wacky writing conflicst between the httpd process and our
log-filtering program.



Also, what happens if instead of opening up explicit files you use
standard input and output?  Here's a modified program that uses sys.stdin
and sys.stdout:

##
"""Cut really long lines out of the output."""
import sys
for line in sys.stdin:
if len(line) < 2086:
sys.stdout.write(line)
sys.stdin.close()
sys.stdout.close()
##

This can be equivalent to the previous program if we use the shell's file
redirection.  It also allows us to run the program on different input and
output files with ease.  Try it on some other files first and see that it
does work on regular files first.

Best of wishes to you!

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Re: manipulating a file

2005-02-08 Thread Reed L. O'Brien
Shitiz Bansal wrote:
Hi,
I do see a problem.
The script is fine, the problem lies else where.
Your script is trying to write log.bak to log, it
should b other way round.
i.e
srcfile = open('/var/log/httpd-access.log', 'r')
dstfile = open('/var/log/httpd-access.log.bak', 'w')
hope that fixes it.
About the efficiency, why do u need python at all...
How abt a simple shell command
   cat httpd-access.log>>log.bak
Shitiz
--- Danny Yoo <[EMAIL PROTECTED]> wrote:

On Mon, 7 Feb 2005, Reed L. O'Brien wrote:

I want to read the httpd-access.log and remove any
oversized log records
I quickly tossed this script together.  I manually
mv-ed log to log.bak
and touched a new logfile.
running the following with print i uncommented
does print each line to
stdout.  but it doesn't write to the appropriate
file...
Hello!
Let's take a look at the program again:
###
import os
srcfile = open('/var/log/httpd-access.log.bak', 'r')
dstfile = open('/var/log/httpd-access.log', 'w')
while 1:
lines = srcfile.readlines()
if not lines: break
for i in lines:
if len(i) < 2086:
dstfile.write(i)
srcfile.close()
dstfile.close()
###

a) what am I missing?
b) is there a less expensive way to do it?
Hmmm... I don't see anything offhand that prevents
httpd-access.log from
containing the lines you expect.  Do you get any
error messages, like
permission problems, when you run the program?
Can you show us how you are running the program, and
how you are checking
that the resulting file is empty?
Addressing the question on efficiency and expense:
yes.  The program at
the moment tries to read all lines into memory at
once, and this is
expensive if the file is large.  Let's fix this.
In recent versions of Python, we can modify
file-handling code from:
###
lines = somefile.readlines()
for line in lines:
   ...
###
to this:
###
for line in somefile:
   ...
###
That is, we don't need to extract a list of 'lines'
out of a file.
Python allows us to loop directly across a file
object.  We can find more
details about this in the documentation on
"Iterators" (PEP 234):
   http://www.python.org/peps/pep-0234.html
Iterators are a good thing to know, since Python's
iterators are deeply
rooted in the language design.  (Even if it they
were retroactively
embedded.  *grin*)
A few more comments: the while loop appears
unnecessary, since on the
second run-through the loop, we'll have already read
all the lines out of
the file.  (I am assuming that nothing is writing to
the backup file at
the time.)  If the body of a while loop just runs
once, we don't need a
loop.
This simplifies the code down to:
###
srcfile = open('/var/log/httpd-access.log.bak', 'r')
dstfile = open('/var/log/httpd-access.log', 'w')
for line in srcfile:
   if len(line) < 2086:
   dstfile.write(line)
srcfile.close()
dstfile.close()
###
I don't see anything else here that causes the file
writing to fail.  If
you can tell us more information on how you're
checking the program's
effectiveness, that may give us some more clues.
Best of wishes to you!
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


		
__ 
Do you Yahoo!? 
Yahoo! Mail - Helps protect you from nasty viruses. 
http://promotions.yahoo.com/new_mail
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor

I am actually mv log to bak and write the non offening entries back to 
log.  I can not be working on log as it needs to be able to accept new 
entries as the webserver is accessed.  Plus I am learning python, I 
could have sh scripted  it easy but am broadening my horizons...

reed
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Re: Have I run into a limitation of Pickle?

2005-02-08 Thread Javier Ruere
Johan Kohler wrote:
> Hi,
> In the attached code, I'm trying to pickle and unpickle
> (1) an object containing a list of dictionaries.
> (2) an object containing a list objects each containing a dictionary.
> 
[successful usecase]
> 
> but (2) fails with the following error:
> 
> <__main__.User instance at 0x41a56fac>
> <__main__.User instance at 0x41a56f2c>
> Traceback (most recent call last):
>   File "/usr/lib/python2.3/site-packages/sm/scriptutils.py", line 49,
> in  run
> exec codeObject in mainDict
>   File "", line 87, in ?
>   File "", line 79, in loadbroken
>   File "", line 33, in readfromfile
>   File "/usr/lib/python2.3/pickle.py", line 1390, in load
> return Unpickler(file).load()
>   File "/usr/lib/python2.3/pickle.py", line 872, in load
> dispatch[key](self)
>   File "/usr/lib/python2.3/pickle.py", line 1083, in load_inst
> klass = self.find_class(module, name)
>   File "/usr/lib/python2.3/pickle.py", line 1140, in find_class
> klass = getattr(mod, name)
> AttributeError: 'module' object has no attribute 'User'
> Exception raised while running script  
> ---
> 
> I hope this is not a limitation of Pickle, because that would mean I
> have  to change a large section of my code :-(

  Pickle can handle any object but it needs the definition of the class
of the object to be available in order to unpickle.
  For example:

.>>> class A: pass

.>>> a = A()
.>>> import pickle
.>>> s = pickle.dumps(a)
.>>> s
'(i__main__\nA\np0\n(dp1\nb.'
.>>> pickle.loads(s)
<__main__.A instance at 0x403fdcec>
.>>> del A
.>>> pickle.loads(s)
Traceback (most recent call last):
  File "", line 1, in ?
  File "/usr/lib/python2.3/pickle.py", line 1394, in loads
return Unpickler(file).load()
  File "/usr/lib/python2.3/pickle.py", line 872, in load
dispatch[key](self)
  File "/usr/lib/python2.3/pickle.py", line 1083, in load_inst
klass = self.find_class(module, name)
  File "/usr/lib/python2.3/pickle.py", line 1140, in find_class
klass = getattr(mod, name)
AttributeError: 'module' object has no attribute 'A'

  The tracebacks are similar. It seems class User is not available when
unpickling in the second case.

Javier

PS: I have not actually looked at the code so YMMV. :p

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Re: Percolation model in python

2005-02-07 Thread Lee Harr
  I have two questions. Once a MxN world is generated how would you
search for nearest neighbors (to see who is connected) and then color

Does this help?
import random
PERSON, EMPTY = '*', '.'
def get_threshold():
   perc = raw_input("Please enter a thresold between 0-1.   ")
   perc = float(perc)
   return perc
def make_random_world(M, N):
   """Constructs a new random game world of size MxN."""
   perc = get_threshold()
   world = {}
   for j in range(N):
   for i in range(M):
   world[i, j] = percolation(perc)
   world['dimensions'] = (M, N)
   return world
def percolation(perc):
   randval = random.random()
   if randval > perc:
   return EMPTY
   else:
   return PERSON
def neighbors(world, x, y):
   M, N = world['dimensions']
   nxmin = max(0, x-1)
   nxmax = min(M, x+1)
   nymin = max(0, y-1)
   nymax = min(N, y+1)
   r = []
   for nx in range(nxmin, nxmax+1):
   for ny in range(nymin, nymax+1):
   if nx != x or ny != y:
   r.append((nx, ny))
   return r
def print_world(world):
   """Prints out a string representation of a world."""
   M, N = world['dimensions']
   for j in range(N):
   for i in range(M):
   print world[i, j],
   print
def make_world_option():
   m = int(raw_input("Please enter a m dimension.   "))
   n = int(raw_input("Please enter a n dimension.   "))
   raw_input("Press return to make a world")
   return make_random_world(m, n)
def show_neighbors_option(world):
   x = int(raw_input("Please enter an x coord.   "))
   y = int(raw_input("Please enter a y coord.   "))
   print neighbors(world, x, y)
def menu():
   print """
   Please pick your option:
   1) Percolation model for Small Pox
   2) Show world
   3) Instructions
   4) Show neighbors
   5) Exit
   """
   option = int(raw_input("Which option[1,2,3,4,5]? "))
   return option
if __name__ == '__main__':
   option = None
   while option != 5:
   if option == 1:
   world = make_world_option()
   elif option == 2:
   print_world(world)
   elif option == 4:
   show_neighbors_option(world)
   option = menu()
_
Don't just search. Find. Check out the new MSN Search! 
http://search.msn.com/

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Re: variation of Unique items question

2005-02-05 Thread Liam Clarke
When someone joins the list, they shoudl receive a welcome email that
contains -


> - a clear description of what you want to do
> - sample data
> - desired results
> - code that attempts to solve the problem

as a helpful hint of how to ask questions.

I have this bookmarked - 
http://catb.org/~esr/faqs/smart-questions.html

"Never assume you are entitled to an answer. You are not; you aren't,
after all, paying for the service. You will earn an answer, if you
earn it, by asking a question that is substantial, interesting, and
thought-provoking â one that implicitly contributes to the experience
of the community rather than merely passively demanding knowledge from
others."

"RTFM has a younger relative. If you get a reply that reads "STFW",
the person who sent it thinks you should have Searched The F**king
Web. He is almost certainly right. Go search it. (The milder version
of this is when you are told "Google is your friend!")"

"Q: My {program, configuration, SQL statement} doesn't work

A:  

This is not a question, and I'm not interested in playing Twenty
Questions to pry your actual question out of you â I have better
things to do.

Q:  

How can I crack root/steal channel-ops privileges/read someone's email?
A:  

You're a lowlife for wanting to do such things and a moron for asking
a hacker to help you."

Arrogant words of wisdom to ask help by. :- )
(But, some of them seem appropriate here from time to time.)


Liam Clarke
On Fri, 04 Feb 2005 10:02:25 -0500, Kent Johnson <[EMAIL PROTECTED]> wrote:
> I will give some credit to you for asking a clear question. You included
> - a clear description of what you want to do
> - sample data
> - desired results
> - code that attempts to solve the problem
> 
> When all of these are present I am much more likely to respond. The first 
> three elements especially
> make a big difference.
> 
> Kent
> 
> Scott Melnyk wrote:
> > Hello.
> >
> > Kent once again you have responded incredibly quickly in a most
> > helpful manor.  I sometimes wonder if the old reference to a
> > "Kent-bot" has some truth to it.
> >
> > Thanks again, I will play with it and keep on going.
> >
> > Scott
> > ___
> > Tutor maillist  -  Tutor@python.org
> > http://mail.python.org/mailman/listinfo/tutor
> >
> 
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 


-- 
'There is only one basic human right, and that is to do as you damn well please.
And with it comes the only basic human duty, to take the consequences.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Re: Are you allowed to shoot camels? [kinda OT]

2005-02-04 Thread Alan Gauld
> > I think its clearer! It says that the first two things happen
> > or else the last thing. Plain English.
>
> That's apparently subjective then.

So it seems. You always assume that whats clear to you will be
clear to all! This discussion proves it ain't necessarily so...

> eye. (x**2 for x in range(10)) didn't mean anything to me either,
the
> first time I saw it.

Nor me and I knew comprehensions from Haskell. Its taken me about 203
years to get comfortable with LCS inPython.
I really wish they'd stick a marker (| or : or even a $!) between
the first item and the loop:

[x**2 | for x in range(10)]

I'd have found it much easier to grok. And I can't think iof any
syntax rules of expressions it wouuld break. Do we use | as a
bitwise operatorin Python? I don't think so...

> absolutely be useful when judisciously used. Many such lists seem to
> assume that developers can't judge such things for themselves. I
think

Having been involved in creating a couple such coding guidelines
lists I can say from experience that they mostly reflect the problems
the maintenance teams struggle with most. And having led a team
of maintenance C programmers for 2 years I fully sympathise
with the view that programmers can't judge very well. (And that
includes myself, I am well aware that what seems perfectly clear
to me when I write it may not be to some poor sap who has
to fix/enhance it) And remember too that maintenance accounts
for 80% of the cost on most software projects...

Alan G.

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Re: Small GUI toolkit and executable creators

2005-02-04 Thread Andrei
Patrick Kirk wrote on Fri, 04 Feb 2005 21:47:58 +:

> I'm writing an application that will distributed by download and want it 
> to be as small as possible.  The target platform is Windows.

Python isn't the right choice if your aim is minimum "executable" size. I
wouldn't worry too much about it though, people are perfectly used to
downloading multi-megabyte applications and service packs which run into
the hundreds of megabytes.

> For the GUI toolkit, I am looking at wxPython and tkinter.  For a small 
> application with only 4 working forms, which can be expected to produce 
> the smaller programs?

I have no idea. The number of forms is not relevant, since it's the toolkit
that takes up all the space, not the forms. I can tell you that a packaged
wxPython app is roughly 4 MB, don't know about Tkinter. wxPython looks
better (more native) though.

> Has anyone any comments on which produces smaller executables and and if 
> either is qualitively better than the other.

You shouldn't expect much difference in that respect, since they all do
pretty much the same thing: pack up the junk and put an exe stub on it, and
there's only so much compressing you can do.

-- 
Yours,

Andrei

=
Real contact info (decode with rot13):
[EMAIL PROTECTED] Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V ernq
gur yvfg, fb gurer'f ab arrq gb PP.

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


RE: [Tutor] Re: Are you allowed to shoot camels? [kinda OT]

2005-02-04 Thread Smith, Jeff
Roel,

That was well put.  Too many people complain about certain language
features because of the way they are abused independent of whether or
not they have any value when used properly.  In that case it's throwing
the baby out with the bath-water...and won't achieve anything since bad
programmers will be bad programmers no matter how much you try and
constrain them.  And in doing so you manage to prevent good programmers
from creating clear conscise statements that exactly express the logic
that they are trying to impliment.

Jeff


-Original Message-
From: Roel Schroeven [mailto:[EMAIL PROTECTED] 
Sent: Friday, February 04, 2005 2:00 PM
To: tutor@python.org
Subject: [Tutor] Re: Are you allowed to shoot camels? [kinda OT]


In my experience, such lists often go too far in that respect. I agree 
that fall-trough should mostly be avoided (except when multiple values 
should leed to the same branch). Ternary operators can certainly be 
abused (as demonstrated by much of the IOCCC entries), but can 
absolutely be useful when judisciously used. Many such lists seem to 
assume that developers can't judge such things for themselves. I think 
that if you have developers that can't do that, you have worse problems 
than a ternary operator here and there.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Re: Are you allowed to shoot camels? [kinda OT]

2005-02-04 Thread Roel Schroeven
Alan Gauld wrote:
BTW, Steve McConnell recommends your favorite too in Code Complete.
But
he also didn't manage to convince me.

Thats where I first found it, I looked up a couple of references and
the
message was consistent, so I changed my style. (And my emacs settings
:-)
I'll have to read that part of the book again. But I don't have my hopes 
up since three years of using it at work didn't change my feelings about 
it (and not for a lack of trying).

--
"Codito ergo sum"
Roel Schroeven
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Re: Are you allowed to shoot camels? [kinda OT]

2005-02-04 Thread Roel Schroeven
Alan Gauld wrote:
foo = x and y or z
is much less elegant than
foo = x ? y : z
You must be joking too... You think that
x and y or z
is as clear as
x ? y : z

I think its clearer! It says that the first two things happen
or else the last thing. Plain English.
That's apparently subjective then. I know what it means because I've 
read about it, but I still have trouble really grokking it. I don't have 
any problem with 'x and y' or with 'x or y', but somehow the combination 
of the two is one step too many for me.

'?:' means absolutely nothing without somebody to explain it.
But ever since it was explained to me, I can parse it in the blink of an 
eye. (x**2 for x in range(10)) didn't mean anything to me either, the 
first time I saw it.

Interesting, obviously a lot of support for both, yet they are
features I try to avoid in C(*) and never miss in Python. If
given the choice I'd much rather have decent lambdas or
even a repeat/until loop!
I don't really try to avoid them; I just use them when appropriate, 
which is not very often. But in those rare cases, I'm glad I don't have 
to resort to other, less appropriate constructs.

And yes, a decent lambda would be nice indeed. Repeat/until too: I used 
it quite a lot in my Pascal days. But I don't know if it's worth 
cluttering the language up for.

(*)And most software houses I've worked with have ternary
operators on their "do not use" list along with switch fall-throughs.
In my experience, such lists often go too far in that respect. I agree 
that fall-trough should mostly be avoided (except when multiple values 
should leed to the same branch). Ternary operators can certainly be 
abused (as demonstrated by much of the IOCCC entries), but can 
absolutely be useful when judisciously used. Many such lists seem to 
assume that developers can't judge such things for themselves. I think 
that if you have developers that can't do that, you have worse problems 
than a ternary operator here and there.

--
"Codito ergo sum"
Roel Schroeven
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Re: Are you allowed to shoot camels? [kinda OT]

2005-02-04 Thread Alan Gauld
> > 
> > X
> > X
> > X
> >
> > Thats Python! Since you are on this list I suspect you do write
> > "code like that" Its just Guido removed the now extraneous {}...
>
> My favorite, Allman style, is also Python if you remove the {} !

Yep but the braces in Allman completely wreck the block structure

X
XXX
   XX
XXX

> BTW, Steve McConnell recommends your favorite too in Code Complete.
But
> he also didn't manage to convince me.

Thats where I first found it, I looked up a couple of references and
the
message was consistent, so I changed my style. (And my emacs settings
:-)

Alan G.

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Re: Are you allowed to shoot camels? [kinda OT]

2005-02-04 Thread Alan Gauld
> Do you have a link to these studies? I'm always skeptical about the 
> methodology in those studies, but I'm willing to be proven wrong.

Check "Code Complete" by Steve McConnel, he gives the explanation 
and also several references. One that I found from a quick glance 
is "Hansen & Yim, 1987". Also a bibliography(!) on the subject of 
code style is cited: "Edward & Oman in Sigplan Notices Feb 1990".

McConnell has a new version of his book out it may have more 
recent references too, I only have the 1993 edition at hand.

Alan G.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Re: Are you allowed to shoot camels? [kinda OT]

2005-02-04 Thread Alan Gauld
> > foo = x and y or z
> >
> > is much less elegant than
> >
> > foo = x ? y : z
>
> You must be joking too... You think that
>
> x and y or z
>
> is as clear as
>
> x ? y : z

I think its clearer! It says that the first two things happen
or else the last thing. Plain English.

'?:' means absolutely nothing without somebody to explain it.

> Ugly as I think it is, I could live with that. But it's worse:
>
> x and y or z
>
> doesn't even work if y evaluates to False.

Sure I wasn't recommending that and/or is a good idea I just
meant that ugly as it was it was clearer than the meaningless ?:

> As far as I'm concerned, the lack of a proper ternary if/then/else
> operator is a wart in the otherwise very clean design of Python. The
> lack of a switch statement too, but to a much lesser degree.

Interesting, obviously a lot of support for both, yet they are
features I try to avoid in C(*) and never miss in Python. If
given the choice I'd much rather have decent lambdas or
even a repeat/until loop!

(*)And most software houses I've worked with have ternary
operators on their "do not use" list along with switch fall-throughs.
BTW I do confess that if switch exists I will use it where I can't
use OOP or a dictionary to avoid it - like in vanilla C...!

Alan G.

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Re: This Deletes All my Files

2005-02-04 Thread Chad Crabtree
Thank you all for answering my question.  I thought it would be some 
misunderstanding on my part.  The example Andrei made was very
telling.

Andrei wrote:

s = "d:/tests/test.txt"
class dummyfile(object):


>... def open(self, *args):
>... print "dummyfile.open:", args
>... def write(self, *args):
>... print "dummyfile.write:", args
>... def read(self, *args):
>... print "dummyfile.read:", args
>... return ""
>  
>
def dummyopen(filename, type):


>... print "dummyopen:", filename, type
>... d = dummyfile()
>... d.open(filename, type)
>... return d
>
>  
>
dummyopen(s, 'w').write(dummyopen(s, 'r').read())


>dummyopen: d:/tests/test.txt w
>dummyfile.open: ('d:/tests/test.txt', 'w') <--- first open for
writing
>dummyopen: d:/tests/test.txt r
>dummyfile.open: ('d:/tests/test.txt', 'r') <--- then for reading
>dummyfile.read: ()
>dummyfile.write: ('',)
>
>  
>
>>spend 5 hours RTFM.  I got it to work by breaking it up to several 
>>statements, but I would like to know.
>>
>>
>
>And that's the way you *should* write it - code like this doesn't
deserve to
>work anyway :). 
>
>Yours,
>
>Andrei
>
>___
>Tutor maillist  -  Tutor@python.org
>http://mail.python.org/mailman/listinfo/tutor
>
>
>  
>




__ 
Do you Yahoo!? 
The all-new My Yahoo! - Get yours free! 
http://my.yahoo.com 
 

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Re: variation of Unique items question

2005-02-04 Thread Kent Johnson
I will give some credit to you for asking a clear question. You included
- a clear description of what you want to do
- sample data
- desired results
- code that attempts to solve the problem
When all of these are present I am much more likely to respond. The first three elements especially 
make a big difference.

Kent
Scott Melnyk wrote:
Hello.
Kent once again you have responded incredibly quickly in a most
helpful manor.  I sometimes wonder if the old reference to a
"Kent-bot" has some truth to it.
Thanks again, I will play with it and keep on going.
Scott
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Re: variation of Unique items question

2005-02-04 Thread Scott Melnyk
Hello.

Kent once again you have responded incredibly quickly in a most
helpful manor.  I sometimes wonder if the old reference to a
"Kent-bot" has some truth to it.

Thanks again, I will play with it and keep on going.

Scott
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Re: Are you allowed to shoot camels? [kinda OT]

2005-02-04 Thread Roel Schroeven
Chad Crabtree wrote:
How about a concrete example where lambda is more elegant than a
named 
block of code

aList=['a','bb','ccc','','ee']
bList=aList[:] #deep copy
assert not bList is aList
def sortByLength(item1,item2):
return cmp(len(item1),len(item2))
bList.sort(sortByLength)
assert bList==['a', 'bb', 'ee', 'ccc', '']
aList.sort(lambda x,y:cmp(len(x),len(y)))
assert aList==['a', 'bb', 'ee', 'ccc', '']

Now this is a concrete example of how lambda simplifies code, at 
least for me because it does not clutter my mental name space. Also
it is much shorter. However it should be said that this is very much
a question  of taste.
Indeed. In this case, I like the version without lambda. Naming the 
function serves as documentation, so I don't even need to read an 
interpret the body of the function to know what it does. Assuming that 
the name correctly describes the behavior of course, but I need to check 
that only once. From then on, sort(sortByLength) instantly explains what 
it does, while sort(lambda x,y: cmp(len(x),len(y)) needs much more parsing.

But I agree that there are cases where lambda is more useful and/or clearer.
--
"Codito ergo sum"
Roel Schroeven
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Re: Are you allowed to shoot camels? [kinda OT]

2005-02-04 Thread Roel Schroeven
Alan Gauld wrote:
Look at it conceptually:

X
X
X
Thats Python! Since you are on this list I suspect you do write
"code like that" Its just Guido removed the now extraneous {}...
My favorite, Allman style, is also Python if you remove the {} !
BTW, Steve McConnell recommends your favorite too in Code Complete. But 
he also didn't manage to convince me.

--
"Codito ergo sum"
Roel Schroeven
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Re: Are you allowed to shoot camels? [kinda OT]

2005-02-04 Thread Roel Schroeven
Alan Gauld wrote:
In fact the best style of all is neither of the two I showed,
its actually this - which early everyone hates when they see it!
inf f(x)
{
bah()
}
Yikes. We use that style at work. At first I found it ugly, but I 
thought I'd get used to it after a while. Well, 3 years later I still 
find it ugly and, more importantly, much harder to understand the structure.

Do you have a link to these studies? I'm always skeptical about the 
methodology in those studies, but I'm willing to be proven wrong.

--
"Codito ergo sum"
Roel Schroeven
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Re: Are you allowed to shoot camels? [kinda OT]

2005-02-04 Thread Roel Schroeven
Alan Gauld wrote:
I also wish Python would take up the C ternary operator 
which is also quite clear and elegant.

:-)
You joke I assume? ':?' is clear? Its succinct but also 
prone to abuse. I don't think the Python equivalent 

foo = x and y or z
is much less elegant than
foo = x ? y : z
You must be joking too... You think that
x and y or z
is as clear as
x ? y : z
even though the former is just a hack that was not meant to be used as 
such, while the latter is a well-documented feature that is designed to 
do what it does?

Ugly as I think it is, I could live with that. But it's worse:
x and y or z
doesn't even work if y evaluates to False. That alone makes me never 
want to use the construct: whether the expression evaluates to y or z 
should depend on the value of x, not the value of y or z.

As far as I'm concerned, the lack of a proper ternary if/then/else 
operator is a wart in the otherwise very clean design of Python. The 
lack of a switch statement too, but to a much lesser degree.

--
"Codito ergo sum"
Roel Schroeven
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Re: This Deletes All my Files

2005-02-04 Thread Andrei
Chad Crabtree  yahoo.com> writes:

> I've tried this and I cannot figure out why this does not work.  I 
> figure this has something to do with order of operations.  I figured 
> someone would know exactly why it doesn't work.  Wouldn't this start 
> inside parens then from left to right?
> 
> open(item,'w').write(open(item,'r').read().replace(' ',''))

Well, what your code says is this:
1. open item for writing and return a file object
2. call on that file object the write method (at this point its contents are
wiped out)
3. open that same file for reading (but it's empty now)
4. read everything from it (nothing)
5. write nothing back to the file.

You can test it by implementing a dummy open method and a dummy file class which
log what happens to them:

>>> s = "d:/tests/test.txt"
>>> class dummyfile(object):
... def open(self, *args):
... print "dummyfile.open:", args
... def write(self, *args):
... print "dummyfile.write:", args
... def read(self, *args):
... print "dummyfile.read:", args
... return ""
>>> def dummyopen(filename, type):
... print "dummyopen:", filename, type
... d = dummyfile()
... d.open(filename, type)
... return d

>>> dummyopen(s, 'w').write(dummyopen(s, 'r').read())
dummyopen: d:/tests/test.txt w
dummyfile.open: ('d:/tests/test.txt', 'w') <--- first open for writing
dummyopen: d:/tests/test.txt r
dummyfile.open: ('d:/tests/test.txt', 'r') <--- then for reading
dummyfile.read: ()
dummyfile.write: ('',)

> spend 5 hours RTFM.  I got it to work by breaking it up to several 
> statements, but I would like to know.

And that's the way you *should* write it - code like this doesn't deserve to
work anyway :). 

Yours,

Andrei

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Re: Are you allowed to shoot camels? [kinda OT]

2005-02-03 Thread Bill Mill
On Thu, 3 Feb 2005 04:24:06 -0500, Patrick Hall <[EMAIL PROTECTED]> wrote:
> > Beware! Overcome the temptation!
> > Try this: http://kodos.sourceforge.net/
> 
> While I have no problem personally with Perl or PHP, I'll second the
> recommendation for kodos -- it's very useful for learning to use
> regexes in Python.

Ok, I have to ask: why? Whenever I write and debug regexes (as I had
to do this morning for the first time in a while - I try to avoid
them) I always create a function in the interpreter that looks like:

def test(regex, line):
print re.compile(regex).match(line).groups()

and then test my regexes incrementally:

>>>l = '8 this is my line to test'
>>> test('^\s*(\d)+', l)

until I have it right. How is using this tool easier than that?

Peace
Bill Mill
bill.mill at gmail.com

> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Re: Are you allowed to shoot camels? [kinda OT]

2005-02-03 Thread Kent Johnson
Patrick Hall wrote:
Beware! Overcome the temptation!
Try this: http://kodos.sourceforge.net/

While I have no problem personally with Perl or PHP, I'll second the
recommendation for kodos -- it's very useful for learning to use
regexes in Python.
Or, if you don't have Qt available, use the regular expression tester that comes with Python - it's 
at C:\Python24\Tools\Scripts\redemo.py (or whatever the *nix equivalent is).

Kent
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Re: Are you allowed to shoot camels? [kinda OT]

2005-02-03 Thread Patrick Hall
> Beware! Overcome the temptation!
> Try this: http://kodos.sourceforge.net/

While I have no problem personally with Perl or PHP, I'll second the
recommendation for kodos -- it's very useful for learning to use
regexes in Python.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Re: Are you allowed to shoot camels? [kinda OT]

2005-02-03 Thread Wolfram Kraus
Alan Gauld wrote:
[...]
1) I'll use Perl for the regex stuff from now on, Perl is obviously
built for this.

Yes, or PHP. Both have RE baked in.
Beware! Overcome the temptation!
Try this: http://kodos.sourceforge.net/
HTH ;-)
Wolfram
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Re: how to separate hexadecimal

2005-02-02 Thread Alan Gauld
>  >>> hexa = '0x87BE'
>  >>> upper = int(hexa[2:4], 16)
>  >>> lower = int(hexa[4:6], 16)

FWIW :
You don't need to strip the '0x' from the front, int() is 
smart enough to do that automatically for base 16 
conversions...

Alan G.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Re: how to separate hexadecimal

2005-02-02 Thread Wolfram Kraus
jrlen balane wrote:
i have a 4 digit hex number (2 bytes) and i want to separate it into 2
digit hex (1 byte each) meaning i want to get the upper byte and the
lower byte since i am going to add this two.
how am i going to do this?
should i treat it just like a normal string?
please help, thanks.
ex. hexa = '0x87BE"  # what i want to do is:
  a = 0x87, b = 0xBE# so that i could do this:
  c = a + b#which should be equal to 0x145
Not sure where you get hexa from, but given your example you can use 
int(x, base) with base = 16 to convert your string to an integer and 
then use the %x formatstring:
>>> hexa = '0x87BE'
>>> upper = int(hexa[2:4], 16)
>>> lower = int(hexa[4:6], 16)
>>> print '0x%x + 0x%x = 0x%x' % (upper, lower, upper+lower)
0x87 + 0xbe = 0x145

HTH,
Wolfram
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Re: Better structure?

2005-02-01 Thread Jorge Luiz Godoy Filho
Liam Clarke wrote:

>> http://www.cs.bell-labs.com/cm/cs/pearls/
> That link seems to be dead. Pity. My whole programming experience is
> comprised of Ah-Ha's followed by Um's...

It worked here.

-- 
Godoy.  <[EMAIL PROTECTED]>


___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Re: Presentation

2005-02-01 Thread Wolfram Kraus
Paul Hartley wrote:
[...]
When I was a member of the Forth Interest Group in the USA we learned
that Forth was used on the buggy that went to mars, that it started
life controlling huge radio telescopes which only had 4k (yes 4k) of
memory for both language and application.
Well, the rover used Forth, but the rover-website is Plone powered:
http://plone.org/newsitems/mars-rover
Plone is a CMS built on top of Zope, which itself is Python powered. For 
more sites running plone see: http://plone.org/about/sites/

HTH,
Wolfram
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Re: sorting a 2 gb file- i shrunk it and turned it around

2005-01-28 Thread Kent Johnson
Scott Melnyk wrote:
Hello again!
Thank you everyone for all the help.
Congratulations on getting this working!
I can see where any of the chains appear more than once, which is good
and I am looking for situations like first example where
ENST0339563.1 is the first and third on the list or the fifth
example.
Next step is to cut out the ENST lines that only show up once and wind
up with just the places where there are matches at least twice to a
given transcript (using the ENST0...) ids.  Like in the final
example I only want the first and third so I know it is twice in that
transcript.
See the tutor thread "Unique items in lists" if you need help with this step, we just had an 
extensive discussion of how to do it.

Kent
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Re: sorting a 2 gb file- i shrunk it and turned it around

2005-01-28 Thread Scott Melnyk
Hello again!

Thank you everyone for all the help.  The most important step in
dealing with Blast results is getting rid of all the extraneous
information.  The standard result file gives you everything you could
ask for when comparing DNA sequences, however at this step I am
looking for specific data.  Once I have my relevant matches I can go
back and pull out the info for just those matches from the file.

Following Kent's advice I came up with the following (I should set up
defs and a modular system for renewability, that will be next)

import sys   #my system complained when I had them on 1 line as sys, sets, re
import sets  #not sure why but that's another issue (2.4 on win XP)
import re

result=re.compile('^(hg17.+)5\'.+')  #the import part of the line is in the ( )
query=re.compile('^.+(ENST\d+\.\d)+') #matches the line up to the
important transcriptID
   #and groups the ID info

TFILE = open(sys.argv[1], 'r' ) #file to read from
WFILE=open(sys.argv[2], 'w') # file to write to

results={}

for line in TFILE:
isQueryLine= query.match(line)
isResultLine= result.match(line)
if isQueryLine:
current_query = isQueryLine.group(1)
if isResultLine:
key = isResultLine.group(1)
results.setdefault(key, []).append(current_query) # see
explanation below



# Now go through results looking for entries with more than one query
for key, queries in results.iteritems():
  if len(queries) > 1:
print >> WFILE
print >> WFILE, key
for query in queries:
  print >> WFILE, query

I am almost there the program seemed to run well will minimal swapping
and finished in 5 minutes. My output file is only 45 mb.

A sample of the output file is:


hg17_chainMm5_chr15 range=chr7:148238502-148239073
ENST0339563.1
ENST0342196.1
ENST0339563.1
ENST0344055.1

hg17_chainMm5_chr13 range=chr5:42927967-42928726
ENST0279800.3
ENST0309556.3

hg17_chainMm5_chr6 range=chr1:155548627-155549517
ENST0321157.3
ENST0256324.4

hg17_chainMm5_chr13 range=chr1:81386270-81386967
ENST0011649.3
ENST0348636.1

hg17_chainMm5_chr19 range=chr11:56050656-56051559
ENST0341231.1
ENST0341231.1
ENST0331792.1
ENST0341231.1
ENST0341231.1
ENST0331792.1

hg17_chainMm5_chr9 range=chr11:123561223-123562097
ENST0341493.1
ENST0318666.4
ENST0341493.1

I can see where any of the chains appear more than once, which is good
and I am looking for situations like first example where
ENST0339563.1 is the first and third on the list or the fifth
example.
Next step is to cut out the ENST lines that only show up once and wind
up with just the places where there are matches at least twice to a
given transcript (using the ENST0...) ids.  Like in the final
example I only want the first and third so I know it is twice in that
transcript.

Back to it and other things.  Thanks for all the help so far,
Scott
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Re: Syntax Check

2005-01-27 Thread Chad Crabtree
I'm going to look more in to import hooks.  I am only looking for 
syntactic sugar, at least at this point.  It's not really my ambition
to 
make more efficient code. 

To Ryan.  I looked at COG before (not in this case but general
looking 
at python packages) it doesn't really do what I was thinking, but I
can 
see how it would be very useful for it's problem domain of code 
generation for other languages.

Javier Ruere wrote:

>  Yes. To add new stuff to the language you would have to work at
the
>interpreter level. Probably you can avoid going too deep using
import
>hooks, as it has already been suggested, to modify what's being
imported
>on the fly.
>  I believe it could work like Psyco if the preprocessor installed
the
>import hooks when imported.
>  Are you interested only in the syntactic sugar or you plan to
generate
>more efficient code?
>  
>



__ 
Do you Yahoo!? 
The all-new My Yahoo! - Get yours free! 
http://my.yahoo.com 
 

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Re: Syntax Check

2005-01-27 Thread Javier Ruere
Chad Crabtree wrote:
> Ok I'll explain what I've done so far.
[...]
> I hope I made myself clearer.

  Yes. To add new stuff to the language you would have to work at the
interpreter level. Probably you can avoid going too deep using import
hooks, as it has already been suggested, to modify what's being imported
on the fly.
  I believe it could work like Psyco if the preprocessor installed the
import hooks when imported.
  Are you interested only in the syntactic sugar or you plan to generate
more efficient code?

Javier

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Re: Unique Items in Lists

2005-01-27 Thread Brian van den Broek
Kent Johnson said unto the world upon 2005-01-27 16:08:
Brian van den Broek wrote:

Finally, in the first instance, I was aiming for the OP's stated end. 
To make this more general and reusable, I think I'd do:


def get_list_dup_dict(a_list, threshold=1):
items_dict, dup_dict = {}, {}   # Question below
for i in a_list:
items_dict[i] = items_dict.get(i, 0) + 1
for k, v in items_dict.iteritems():
if v >= threshold:
dup_dict[k] = v#Question below
return dup_dict
def print_list_dup_report(a_list, threshold=1):
dup_dict = get_list_dup_dict(a_list, threshold)
for k, v in sorted(dup_dict.iteritems()):
print '%s occurred %s times' %(k, v)

My question (from comment in new code):
Since I've split the task into two functions, one to return a 
duplication dictionary, the other to print a report based on it, I 
think the distinct dup_dict is needed. (I do want the 
get_list_dup_dict function to return a dict for possible use in other 
contexts.)

You could have a function that gets all of the counts, and then filter 
on threshold when you print.

Am I overlooking yet another dict technique that would help, here? Any 
other improvements?
Thanks Kent. Above the last snip would indeed be one such improvement! 
(How'd I miss that?)

Best,
Brian vdB
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Re: Unique Items in Lists

2005-01-27 Thread Kent Johnson
Brian van den Broek wrote:
incorporating some of Wolfram's and Kent's (hope I've missed no one) 
suggestions:


def dups_in_list_report(a_list):
'''Prints a duplication report for a list.'''
items_dict = {}
for i in a_list:
items_dict[i] = items_dict.get(i, 0) + 1
for k, v in sorted(items_dict.iteritems()):   # cf below
if v > 1:
print '%s occurred %s times' %(k, v)

And, I can't but agree that this is much better! Thanks folks.
In trying to improve the code, I first had:
for key in sorted(items_dict.keys()):
if items_dict[key] > 1:
print '%s occurred %s times' %(key, items_dict[key])
in place of the for loop over .iteritems(). Am I right in thinking that 
the advantage of Kent's suggestion of .iteritems() is that it eliminates 
some of the dict lookups? Other advantages?
iteritems() doesn't create an intermediate list so that should be a slight time and memory savings. 
And my guess is that it is faster because it saves the lookups but if you care you should test. 
Mostly I prefer iteritems() because it seems cleaner and clearer to me.

Finally, in the first instance, I was aiming for the OP's stated end. To 
make this more general and reusable, I think I'd do:


def get_list_dup_dict(a_list, threshold=1):
'''Returns a dict of items in list that occur threshold many times
threshold defaults to 1. The dict returned has items occurring at least
threshold many times as keys, and number of occurrences as values.
'''
items_dict, dup_dict = {}, {}   # Question below
for i in a_list:
items_dict[i] = items_dict.get(i, 0) + 1
for k, v in items_dict.iteritems():
if v >= threshold:
dup_dict[k] = v#Question below
return dup_dict
def print_list_dup_report(a_list, threshold=1):
'''Prints report of items in a_list occurring at least threshold 
many times

threshold defaults to 1. get_list_dup_dict(a_list, threshold=0) is 
called.
returning a dict of items in list that occur at least threshold many 
times
as keys and their number of repetitions as values.

This dict is looped over to print a sorted and formatted duplication
report.
'''
dup_dict = get_list_dup_dict(a_list, threshold)
for k, v in sorted(dup_dict.iteritems()):
print '%s occurred %s times' %(k, v)

My question (from comment in new code):
Since I've split the task into two functions, one to return a 
duplication dictionary, the other to print a report based on it, I think 
the distinct dup_dict is needed. (I do want the get_list_dup_dict 
function to return a dict for possible use in other contexts.)
You could have a function that gets all of the counts, and then filter on threshold when you print.
The alternative would be to iterate over a .copy() of the items_dict and 
delete items not meeting the threshold from items_dict, returning the 
pruned items_dict at the end. But, dup_dict is guaranteed to be smaller, 
save for original lists with no duplications and threshold set to 1. So, 
the distinct dup_dict way seems better for memory.

Am I overlooking yet another dict technique that would help, here? Any 
other improvements?
In Python 2.4 I think you could do
dup_dict = dict((k, v) for k, v in items_dict.iteritems() if v >= threshold)
which I think is likely to be quite fast (but again if you care you should 
test).
Kent
Thanks and best to all,
Brian vdB
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Re: Unique Items in Lists

2005-01-27 Thread Brian van den Broek
Kent Johnson said unto the world upon 2005-01-27 05:57:
Brian van den Broek wrote:
Wolfram Kraus said unto the world upon 2005-01-27 03:24:

This whole part can be rewritten (without sorting, but in Py2.4 you 
can use sorted() for this) with a list comprehension (Old Python2.1 
style, with a newer version the keys() aren't needed):
  for k,v in [(k, items_dict[k]) \
  for k in items_dict.keys() if items_dict[k] > 1]:
  print '%s occurred %s times' %(key, items_dict[key])

I think it is clearer to filter the list as it is printed. And 
dict.iteritems() is handy here, too.

for k, v in items_dict.iteritems():
  if v > 1:
print '%s occurred %s times' % (k, v)
Kent
Hi all,
incorporating some of Wolfram's and Kent's (hope I've missed no one) 
suggestions:


def dups_in_list_report(a_list):
'''Prints a duplication report for a list.'''
items_dict = {}
for i in a_list:
items_dict[i] = items_dict.get(i, 0) + 1
for k, v in sorted(items_dict.iteritems()):   # cf below
if v > 1:
print '%s occurred %s times' %(k, v)

And, I can't but agree that this is much better! Thanks folks.
In trying to improve the code, I first had:
for key in sorted(items_dict.keys()):
if items_dict[key] > 1:
print '%s occurred %s times' %(key, items_dict[key])
in place of the for loop over .iteritems(). Am I right in thinking 
that the advantage of Kent's suggestion of .iteritems() is that it 
eliminates some of the dict lookups? Other advantages?

Finally, in the first instance, I was aiming for the OP's stated end. 
To make this more general and reusable, I think I'd do:


def get_list_dup_dict(a_list, threshold=1):
'''Returns a dict of items in list that occur threshold many times
threshold defaults to 1. The dict returned has items occurring at 
least
threshold many times as keys, and number of occurrences as values.
'''

items_dict, dup_dict = {}, {}   # Question below
for i in a_list:
items_dict[i] = items_dict.get(i, 0) + 1
for k, v in items_dict.iteritems():
if v >= threshold:
dup_dict[k] = v #Question below
return dup_dict
def print_list_dup_report(a_list, threshold=1):
'''Prints report of items in a_list occurring at least threshold 
many times

threshold defaults to 1. get_list_dup_dict(a_list, threshold=0) 
is called.
returning a dict of items in list that occur at least threshold 
many times
as keys and their number of repetitions as values.

This dict is looped over to print a sorted and formatted duplication
report.
'''
dup_dict = get_list_dup_dict(a_list, threshold)
for k, v in sorted(dup_dict.iteritems()):
print '%s occurred %s times' %(k, v)

My question (from comment in new code):
Since I've split the task into two functions, one to return a 
duplication dictionary, the other to print a report based on it, I 
think the distinct dup_dict is needed. (I do want the 
get_list_dup_dict function to return a dict for possible use in other 
contexts.)

The alternative would be to iterate over a .copy() of the items_dict 
and delete items not meeting the threshold from items_dict, returning 
the pruned items_dict at the end. But, dup_dict is guaranteed to be 
smaller, save for original lists with no duplications and threshold 
set to 1. So, the distinct dup_dict way seems better for memory.

Am I overlooking yet another dict technique that would help, here? Any 
other improvements?

Thanks and best to all,
Brian vdB
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Re: Syntax Check

2005-01-27 Thread Javier Ruere
Chad Crabtree wrote:
> Does anyone happen to know how to turn of the syntax checking in 
> python?  I've been working on a module driven preprocessor but I'd
> like to not have to use comment strings.

  I don't think that's possible. What would the compiler do with code
with an invalid syntax?
  What's a module driven preprocessor?

Javier

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Re: Unique Items in Lists

2005-01-27 Thread Kent Johnson
Brian van den Broek wrote:
Wolfram Kraus said unto the world upon 2005-01-27 03:24:
Brian van den Broek wrote:

for key in items_dict.copy():   # Try it without the .copy()
if items_dict[key] == 1:# and see what happens.
del items_dict[key]
dict_keys = items_dict.keys()
dict_keys.sort()

for key in dict_keys:
print '%s occurred %s times' %(key, items_dict[key])

This whole part can be rewritten (without sorting, but in Py2.4 you 
can use sorted() for this) with a list comprehension (Old Python2.1 
style, with a newer version the keys() aren't needed):
  for k,v in [(k, items_dict[k]) \
  for k in items_dict.keys() if items_dict[k] > 1]:
  print '%s occurred %s times' %(key, items_dict[key])
I think it is clearer to filter the list as it is printed. And 
dict.iteritems() is handy here, too.
for k, v in items_dict.iteritems():
  if v > 1:
print '%s occurred %s times' % (k, v)
Kent
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Re: Unique Items in Lists

2005-01-27 Thread Brian van den Broek
Wolfram Kraus said unto the world upon 2005-01-27 03:24:
Brian van den Broek wrote:

Thanks Wolfram,
I knew someone would improve what I posted. (It can always be done ;-)
for i in a_list:
if i in items_dict:
items_dict[i] = items_dict[i] + 1
else:
items_dict[i] = 1
get(key, default) is your friend here:
  for i in a_list:
  items_dict[i] = items_dict.get(i, 0) + 1
get() (and his "brother" setdefault()) are mighty dictionary-methods.
What a brain fart I had! I even got as far as reading then entry in 
the Library Ref Mapping Types table for setdefault, 'cause I knew 
there was a way to do this, but couldn't recall it. How they expect me 
to find it when they hide it on the previous line I'll never know ;-) 
/ :-[

for key in items_dict.copy():   # Try it without the .copy()
if items_dict[key] == 1:# and see what happens.
del items_dict[key]
dict_keys = items_dict.keys()
dict_keys.sort()
 >
for key in dict_keys:
print '%s occurred %s times' %(key, items_dict[key])
This whole part can be rewritten (without sorting, but in Py2.4 you can 
use sorted() for this) with a list comprehension (Old Python2.1 style, 
with a newer version the keys() aren't needed):
  for k,v in [(k, items_dict[k]) \
  for k in items_dict.keys() if items_dict[k] > 1]:
  print '%s occurred %s times' %(key, items_dict[key])
I knew sorted() only from the 'What's New in 2.4'. Thanks for 
reminding me to look closer.

I get that the for loops in mine are more costly than the list comps 
in yours. But, I can't help but feel that the list comp isn't as clear 
or readable. Of course, that may say more about me (and the fact that 
while I can read list comps, they aren't really in my working 
vocabulary yet) than it does about the code. I think I like the way I 
wrote it in that it breaks the discrete steps apart. But, for long 
lists, that will be a performance bite indeed.

(I went from my first posts being too concerned about speed to not 
giving a toss. Perhaps the pendulum needs to swing back a bit.)

Anyway, thanks for showing me (and the OP) these alternatives!
Best,
Brian vdB
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Re: Unique Items in Lists

2005-01-27 Thread Wolfram Kraus
Chad Crabtree wrote:
Ok you got me thinking.  I used the same thing I posted before but 
created a one liner that as a side affect makes adict like before. 
[adict.__setitem__(x,adict.get(x,0)+1) for x in l]

I think it's kinda funny and ugly, ohh and not particuarly clear 
about what it does.

Uhh, list-comprehensions with side effects. Must. resist.
And now write the Zen of Python 10 times ;-)
Greetings,
Wolfram
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Re: Unique Items in Lists

2005-01-27 Thread Chad Crabtree
Ok you got me thinking.  I used the same thing I posted before but 
created a one liner that as a side affect makes adict like before.
[adict.__setitem__(x,adict.get(x,0)+1) for x in l]

I think it's kinda funny and ugly, ohh and not particuarly clear
about 
what it does.

Wolfram Kraus wrote:

> get(key, default) is your friend here:
>   for i in a_list:
>   items_dict[i] = items_dict.get(i, 0) + 1
>
> get() (and his "brother" setdefault()) are mighty
dictionary-methods.
>



__ 
Do you Yahoo!? 
Take Yahoo! Mail with you! Get it on your mobile phone. 
http://mobile.yahoo.com/maildemo 
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Re: Unique Items in Lists

2005-01-27 Thread Wolfram Kraus
Brian van den Broek wrote:
[...]
Hi Srini,
for the task of finding out which items are repeated and how many times, 
I'd do this:


def dups_in_list_report(a_list):
'''Prints a duplication report for a list.'''
items_dict = {}
for i in a_list:
if i in items_dict:
items_dict[i] = items_dict[i] + 1
else:
items_dict[i] = 1
get(key, default) is your friend here:
  for i in a_list:
  items_dict[i] = items_dict.get(i, 0) + 1
get() (and his "brother" setdefault()) are mighty dictionary-methods.
for key in items_dict.copy():   # Try it without the .copy()
if items_dict[key] == 1:# and see what happens.
del items_dict[key]
dict_keys = items_dict.keys()
dict_keys.sort()
>
for key in dict_keys:
print '%s occurred %s times' %(key, items_dict[key])
This whole part can be rewritten (without sorting, but in Py2.4 you can 
use sorted() for this) with a list comprehension (Old Python2.1 style, 
with a newer version the keys() aren't needed):
  for k,v in [(k, items_dict[k]) \
  for k in items_dict.keys() if items_dict[k] > 1]:
  print '%s occurred %s times' %(key, items_dict[key])

f = [1,1,2,3,3,3,3,4,4,4,4,4,4,4,5]
dups_in_list_report(f)

And, now that I get back on-line, I see that Chad posted the same basic 
idea. But, perhaps the extra stuff here is of use, too.
You can apply the get()  there, too ;-)

HTH,
Brian vdB

HTH,
Wolfram
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Re: Import Site Failed Resolution

2005-01-25 Thread Kent Johnson
Ah. Do you have a file called os.py or os.pyc in your python files? Taking another look at your 
import trace, I see that site.pyc is found at c:\python24\lib\site.pyc but os.pyc is found in the 
current directory.

Kent
jhomme wrote:
Hi Kent,
my os.py looks like what you posted below. I re-installed after deleting the 
registry key and the
python24 folder. I also discovered that if I type python while pointing right 
at the python24
directory rather than the directory my python files are in, I don't get the 
error.
Weird eh?
Thanks.
Jim
 -Original message-
From: Kent Johnson [EMAIL PROTECTED]
Date: Tue, 25 Jan 2005 14:42:09 -0500
To: 
Subject: Re: [Tutor] Re: Import Site Failed Resolution


OK, getting closer. import site is failing because site imports os and that import is failing. The 
error message points to a line that should be part of the docstring at the beginning of os.py...strange.

Here are the first 22 lines from my os.py - the entire docstring. If your Python2.4\Lib\os.py 
doesn't look like this then you could try pasting in these lines instead, or maybe reinstalling to 
make sure nothing else is corrupted...

 Next line is start of os.py 
r"""OS routines for Mac, DOS, NT, or Posix depending on what system we're on.
This exports:
  - all functions from posix, nt, os2, mac, or ce, e.g. unlink, stat, etc.
  - os.path is one of the modules posixpath, ntpath, or macpath
  - os.name is 'posix', 'nt', 'os2', 'mac', 'ce' or 'riscos'
  - os.curdir is a string representing the current directory ('.' or ':')
  - os.pardir is a string representing the parent directory ('..' or '::')
  - os.sep is the (or a most common) pathname separator ('/' or ':' or '\\')
  - os.extsep is the extension separator ('.' or '/')
  - os.altsep is the alternate pathname separator (None or '/')
  - os.pathsep is the component separator used in $PATH etc
  - os.linesep is the line separator in text files ('\r' or '\n' or '\r\n')
  - os.defpath is the default search path for executables
  - os.devnull is the file path of the null device ('/dev/null', etc.)
Programs that import and use 'os' stand a better chance of being
portable between different platforms.  Of course, they must then
only use functions that are defined by all platforms (e.g., unlink
and opendir), and leave all pathname manipulation to os.path
(e.g., split and join).
"""
 End of snippet from os.py 
Kent

jhomme wrote:
Hi,
Here is all the information I could get from the display of the output from 
this error. How do I figure out what is going on and fix the problem? This is 
on a Windows 2000 machine.
graphic 910  C:\WINNT\system32\command.com
C:\PYTHON>python -v
# installing zipimport hook
import zipimport # builtin
# installed zipimport hook
# c:\python24\lib\site.pyc matches c:\python24\lib\site.py
import site # precompiled from c:\python24\lib\site.pyc
import os # precompiled from os.pyc
'import site' failed; traceback:
Traceback (most recent call last):
File "c:\python24\lib\site.py", line 61, in ?
import os
File "c:\python24\lib\os.py", line 4, in ?
- all functions from posix, nt, os2, mac, or ce, e.g. unlink, stat, etc.
AttributeError: 'module' object has no attribute 'path'
# c:\python24\lib\warnings.pyc matches c:\python24\lib\warnings.py
import warnings # precompiled from c:\python24\lib\warnings.pyc
# c:\python24\lib\types.pyc matches c:\python24\lib\types.py
import types # precompiled from c:\python24\lib\types.pyc
# c:\python24\lib\linecache.pyc matches c:\python24\lib\linecache.py
import linecache # precompiled from c:\python24\lib\linecache.pyc
import os # precompiled from os.pyc
Python 2.4 (#60, Nov 30 2004, 11:49:19) [MSC v.1310 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
Thanks.
Jim
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Re: Import Site Failed Resolution

2005-01-25 Thread Kent Johnson
OK, getting closer. import site is failing because site imports os and that import is failing. The 
error message points to a line that should be part of the docstring at the beginning of os.py...strange.

Here are the first 22 lines from my os.py - the entire docstring. If your Python2.4\Lib\os.py 
doesn't look like this then you could try pasting in these lines instead, or maybe reinstalling to 
make sure nothing else is corrupted...

 Next line is start of os.py 
r"""OS routines for Mac, DOS, NT, or Posix depending on what system we're on.
This exports:
  - all functions from posix, nt, os2, mac, or ce, e.g. unlink, stat, etc.
  - os.path is one of the modules posixpath, ntpath, or macpath
  - os.name is 'posix', 'nt', 'os2', 'mac', 'ce' or 'riscos'
  - os.curdir is a string representing the current directory ('.' or ':')
  - os.pardir is a string representing the parent directory ('..' or '::')
  - os.sep is the (or a most common) pathname separator ('/' or ':' or '\\')
  - os.extsep is the extension separator ('.' or '/')
  - os.altsep is the alternate pathname separator (None or '/')
  - os.pathsep is the component separator used in $PATH etc
  - os.linesep is the line separator in text files ('\r' or '\n' or '\r\n')
  - os.defpath is the default search path for executables
  - os.devnull is the file path of the null device ('/dev/null', etc.)
Programs that import and use 'os' stand a better chance of being
portable between different platforms.  Of course, they must then
only use functions that are defined by all platforms (e.g., unlink
and opendir), and leave all pathname manipulation to os.path
(e.g., split and join).
"""
 End of snippet from os.py 
Kent

jhomme wrote:
Hi,
Here is all the information I could get from the display of the output from 
this error. How do I figure out what is going on and fix the problem? This is 
on a Windows 2000 machine.
graphic 910  C:\WINNT\system32\command.com
C:\PYTHON>python -v
# installing zipimport hook
import zipimport # builtin
# installed zipimport hook
# c:\python24\lib\site.pyc matches c:\python24\lib\site.py
import site # precompiled from c:\python24\lib\site.pyc
import os # precompiled from os.pyc
'import site' failed; traceback:
Traceback (most recent call last):
File "c:\python24\lib\site.py", line 61, in ?
import os
File "c:\python24\lib\os.py", line 4, in ?
- all functions from posix, nt, os2, mac, or ce, e.g. unlink, stat, etc.
AttributeError: 'module' object has no attribute 'path'
# c:\python24\lib\warnings.pyc matches c:\python24\lib\warnings.py
import warnings # precompiled from c:\python24\lib\warnings.pyc
# c:\python24\lib\types.pyc matches c:\python24\lib\types.py
import types # precompiled from c:\python24\lib\types.pyc
# c:\python24\lib\linecache.pyc matches c:\python24\lib\linecache.py
import linecache # precompiled from c:\python24\lib\linecache.pyc
import os # precompiled from os.pyc
Python 2.4 (#60, Nov 30 2004, 11:49:19) [MSC v.1310 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
Thanks.
Jim
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Re: Import Site Failed Resolution

2005-01-25 Thread jhomme
Hi,
Here is all the information I could get from the display of the output from 
this error. How do I figure out what is going on and fix the problem? This is 
on a Windows 2000 machine.

graphic 910  C:\WINNT\system32\command.com
C:\PYTHON>python -v
# installing zipimport hook
import zipimport # builtin
# installed zipimport hook
# c:\python24\lib\site.pyc matches c:\python24\lib\site.py
import site # precompiled from c:\python24\lib\site.pyc
import os # precompiled from os.pyc
'import site' failed; traceback:
Traceback (most recent call last):
File "c:\python24\lib\site.py", line 61, in ?
import os
File "c:\python24\lib\os.py", line 4, in ?
- all functions from posix, nt, os2, mac, or ce, e.g. unlink, stat, etc.
AttributeError: 'module' object has no attribute 'path'
# c:\python24\lib\warnings.pyc matches c:\python24\lib\warnings.py
import warnings # precompiled from c:\python24\lib\warnings.pyc
# c:\python24\lib\types.pyc matches c:\python24\lib\types.py
import types # precompiled from c:\python24\lib\types.pyc
# c:\python24\lib\linecache.pyc matches c:\python24\lib\linecache.py
import linecache # precompiled from c:\python24\lib\linecache.pyc
import os # precompiled from os.pyc
Python 2.4 (#60, Nov 30 2004, 11:49:19) [MSC v.1310 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>>

Thanks.

Jim

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Re: glob or filter help

2005-01-24 Thread Jeff Shannon
Barnaby Scott wrote:
For anyone who doesn't like lambda, how about
import os
def get_fles(exts, upd_dir):
return [i for i in os.listdir(upd_dir) if i.split('.')[-1] in exts]
Better would be:
def get_fles(exts, upd_dir):
return [fname for fname in os.listdir(upd_dir) if \
   os.path.splitext(fname)[-1] in exts \
   and not fname.islink() ]
(This is split into three lines for readability, but can be entered as 
a single line.  Also, the '\' line-continuation is optional, as Python 
will see that the list comp is still open and automatically continue 
the line...)

Using os.path.splitext() to get the extension is safer and more 
portable than simply splitting on '.', and it's self-documenting too! 
 (A month from now, you might need to think a moment to figure out 
why you're splitting on '.', but the very name os.path.splitext() 
tells you about the intent.)

Note that there's a slight difference here, in that exts will need to 
list extensions *with* the leading '.' because splitext() will leave 
it on --

>>> os.path.splitext('filename.txt')
('filename', '.txt')
>>>
I've also added a second clause to ensure that returned files are not 
links, as per the rest of the O.P.'s spec.

Jeff Shannon
Technician/Programmer
Credit International
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Re: Print record x in a file

2005-01-23 Thread Kent Johnson
David Holland wrote:
Kent,
I know that you know far more about python than me but
is that right ?
I created file with 4 records and this code did print
them all randomly:-
import random
i = 0
while i < 10:
file = open('filename')
listcontents = file.readlines()
file.close()
lenoflist = len(listcontents)-1
x = random.randrange(0,lenoflist)
print listcontents[x], i
i = i +1
While although this code below does work many times
nothing is printed out.
import random
i = 0
while i < 10:
file = open('test.rantxt')
listcontents = file.readlines()
file.close()
lenoflist = len(listcontents)#-1
x = random.randrange(0,lenoflist)
print listcontents[x], i
i = i +1
It sounds like your file has a blank line at the end. What do you get if you print 
len(listcontents)? Is it 4 or 5? Where do you think 'nothing' is coming from?

Try this:
import random
listcontents = [1,2,3,4]
for i in range(10):
lenoflist = len(listcontents)-1
x = random.randrange(0,lenoflist)
print listcontents[x]
I never get a 4...
Kent
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


RE: [Tutor] Re: glob or filter help

2005-01-22 Thread Barnaby Scott
For anyone who doesn't like lambda, how about

import os
def get_fles(exts, upd_dir):
return [i for i in os.listdir(upd_dir) if i.split('.')[-1] in exts]



 >  -Original Message-
 >  From: [EMAIL PROTECTED]
 >  [mailto:[EMAIL PROTECTED] 
 >  Behalf Of Javier
 >  Ruere
 >  Sent: 22 January 2005 16:25
 >  To: tutor@python.org
 >  Subject: [Tutor] Re: glob or filter help
 >  
 >  
 >  Jay Loden wrote:
 >  > Thanks! That's exactly the kind of feedback I was looking for.  If
 >  it's not
 >  > too much trouble, do you think you could explain how 
 >  lambda works, or
 >  just
 >  > point me towards a lambda explanation/tutorial that a new 
 >  programmer can
 >  > understand?  It seems to give you some great power but I 
 >  really don't
 >  > understand how it works.
 >  
 >Lambda defines anonymous functions. It has some 
 >  restrictions like that
 >  the function must be expressed in one line and there can be no
 >  assigments. The syntax can be found in [1].
 >Though I personaly like this keyword, I must say that it 
 >  can make code
 >  less readable so I tend to use it for only for extremely simple
 >  snippets. The example given in the previous mail is almost 
 >  too big. But
 >  then again, one must try things out to learn so use it and 
 >  find your own
 >  balance.
 >Also the BDFL has said he is unhappy with lambda (and 
 >  filter, reduce
 >  and map) so he may remove this keyword in the future (but not before
 >  Python3000)[2].
 >  
 >  Javier
 >  
 >  [1] http://www.python.org/doc/2.4/ref/lambdas.html
 >  [2] Look in the user list if you want to learn more about 
 >  this topics.
 >  
 >  ___
 >  Tutor maillist  -  Tutor@python.org
 >  http://mail.python.org/mailman/listinfo/tutor
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Re: glob or filter help

2005-01-22 Thread Javier Ruere
Jay Loden wrote:
> Thanks! That's exactly the kind of feedback I was looking for.  If
it's not
> too much trouble, do you think you could explain how lambda works, or
just
> point me towards a lambda explanation/tutorial that a new programmer can
> understand?  It seems to give you some great power but I really don't
> understand how it works.

  Lambda defines anonymous functions. It has some restrictions like that
the function must be expressed in one line and there can be no
assigments. The syntax can be found in [1].
  Though I personaly like this keyword, I must say that it can make code
less readable so I tend to use it for only for extremely simple
snippets. The example given in the previous mail is almost too big. But
then again, one must try things out to learn so use it and find your own
balance.
  Also the BDFL has said he is unhappy with lambda (and filter, reduce
and map) so he may remove this keyword in the future (but not before
Python3000)[2].

Javier

[1] http://www.python.org/doc/2.4/ref/lambdas.html
[2] Look in the user list if you want to learn more about this topics.

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Re: glob or filter help

2005-01-22 Thread Kent Johnson
Javier Ruere wrote:
Jay Loden wrote:
I have the following code in my updates script (gets the five most recent 
updated files on my site)

def get_fles(exts, upd_dir):
'''return list of all the files matching any extensions in list exts'''
fle_list = [] 
for each in exts:
 cmd = upd_dir + "*." + each
 ext_ls = glob.glob(cmd)
 fle_list = fle_list + ext_ls
return filter(notlink, fle_list)

I wanted to just get one list, of all the .htm and .exe files in my upd_dir.  
I was trying to make a far more elegant solution that what's above, that 
could generate a list through a filter.  Is there a way to trim the code down 
to something that does ONE sort through the directory and picks up the .htm 
and .exe files? (note, it is not necessary for this to recurse through 
subdirectories in the upd_dir). I have cmd defined above because calling
"glob.glob(upd_dir + "*." + each) returned the error "cannot concatenate 
string and list objects" - is this the only way around that, or is there a 
better way?
Breaking out the expression and assigning it to a variable shouldn't make any difference. Are you 
sure you didn't have something like this?
  glob.glob(upd_dir + "*." + exts)

That would give the error message you cite.
In general if you have a question about an error, please post the exact error message including the 
stack trace, it can be very helpful.

  If the filter criteria is complex, it deserves it's own function:

import os
import os.path
def get_files(exts, upd_dir):
... def criteria(filename):
... return filename.split('.')[-1] in exts \
... and not os.path.islink(filename)
... return filter(criteria, os.listdir(upd_dir))
...
get_files(('gz', 'conf'), '.')
['dynfun.pdf.gz', 'twander-3.160.tar.gz', 'PyCon2004DocTestUnit.pdf.gz',
'arg23.txt.gz', '.fonts.conf']
Javier's solution is good. You could also make a regular expression to look for the desired 
extensions. Here is one way:

import os, re
def get_files(exts, upd_dir):
extnMatch = re.compile('(%s)$' % '|'.join(map(re.escape, exts)))
def criteria(filename):
return extnMatch.search(filename) \
and not os.path.islink(filename)
return filter(criteria, os.listdir(upd_dir))
print get_files(['.java', '.txt'], '.')
I better pick apart the extnMatch line a bit...what it does is build a regular expression that 
matches any of the extensions if they occur at the end of the filename.

 >>> exts = ['.java', '.txt']
First I use map() to apply re.escape() to each extension. This escapes any characters in the 
extension that have special meaning in a regex; specifically the '.':
 >>> e1 = map(re.escape, exts)
 >>> e1
['\\.java', '\\.txt']

I could also have used a list comprehension
e1 = [ re.escape(ext) for ext in exts ]
but for applying a function like this I usually use map()
Next I join the individual extensions with '|'. In a regex this selects between 
alternatives.
 >>> e2 = '|'.join(e1)
 >>> e2
'\\.java|\\.txt'
Finally I put the alternatives in parentheses to group them and add a '$' at the end meaning 'match 
the end of the string.
 >>> e3 = '(%s)$' % e2
 >>> e3
'(\\.java|\\.txt)$'

This solution is definitely harder to explain than Javier's :-)
Kent
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Re: glob or filter help

2005-01-21 Thread Javier Ruere
Jay Loden wrote:
> I have the following code in my updates script (gets the five most recent 
> updated files on my site)
> 
> def get_fles(exts, upd_dir):
>  '''return list of all the files matching any extensions in list exts'''
>  fle_list = [] 
>  for each in exts:
>   cmd = upd_dir + "*." + each
>   ext_ls = glob.glob(cmd)
>   fle_list = fle_list + ext_ls
>  return filter(notlink, fle_list)
> 
> I wanted to just get one list, of all the .htm and .exe files in my upd_dir.  
> I was trying to make a far more elegant solution that what's above, that 
> could generate a list through a filter.  Is there a way to trim the code down 
> to something that does ONE sort through the directory and picks up the .htm 
> and .exe files? (note, it is not necessary for this to recurse through 
> subdirectories in the upd_dir).  I have cmd defined above because calling
> "glob.glob(upd_dir + "*." + each) returned the error "cannot concatenate 
> string and list objects" - is this the only way around that, or is there a 
> better way?

  How about:

>>> import os
>>> exts = ('gz', 'conf')
>>> upd_dir = '.'
>>> filter(lambda fn : fn.split('.')[-1] in exts, os.listdir(upd_dir))

  Do you like this better. It doesn't use glob and is terse.

> Also in the above code, "notlink" is just a function that returns True if 
> "islink()" returns truethere has to be a better way to use this with 
> filter(), how can i make filter use "if islink()!=true" as its condition?

  If the filter criteria is complex, it deserves it's own function:

>>> import os
>>> import os.path
>>> def get_files(exts, upd_dir):
... def criteria(filename):
... return filename.split('.')[-1] in exts \
... and not os.path.islink(filename)
... return filter(criteria, os.listdir(upd_dir))
...
>>> get_files(('gz', 'conf'), '.')
['dynfun.pdf.gz', 'twander-3.160.tar.gz', 'PyCon2004DocTestUnit.pdf.gz',
'arg23.txt.gz', '.fonts.conf']


Javier

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Re: Fw: Please submit to tutor list: dictionary update prob

2005-01-21 Thread Jacob S.
Just one question...
Why are you off the list?
I see no point.
If you want to stop getting the mail, you can change the options of your 
list account online...
That's the only reason I see...

Let's see -- reasons
1. Cost -- No, it's free
2. Security -- If you were subscribed to it once, it's too late to worry 
about that (Though there is no reason to)
   a. There is an option (in Outlook Express at least) to make your name 
invisible to others when emailing
   b. You can make your name invisible on the subscriber's list on the 
website by using the options in your account page

Anyone want to comment --  maybe a link to get him to the subscriber's 
option page?

HTH,
Jacob Schmidt 

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Re: Fw: Please submit to tutor list: dictionary update prob

2005-01-20 Thread Kent Johnson

Eri Mendz wrote:
Kent Johnson  tds.net> writes:

Jacob S. wrote:
sorry to send this to you but if you may, kindly send to tutor list as im
no longer subscribed.  my problem is in the update dict portion: it just
doesnt update regardless how many contacts i add. kindly advise where
my mistake is or code gone wrong. the rest of the options i will do on my
own so just hold off the helps for now. appreciate all your good help.

def update_dict(d, f):
  ''' update the saved dictionary file '''
  read = open(f, 'rb')
  newdic = cPickle.load(read)
  newdic.update(d)
  read.close()
You don't do anything with newdic. My guess is you want to dump it back to the
file so it is saved.
this is what i tried:
read = open(f, 'rb')
newdic = cPickle.load(read)
newdic.update(d)
read.close()
write = open(f, 'wb')
cPickle.dump(f, write)
You still aren't doing anything with newdic. The absence of 'newdic' in the code after 
'read.close()' should be a clue :-)

Check the docs on pickle.dump() (which is the same as cPickle.dump()):
dump(  	obj, file[, protocol[, bin]])
Write a pickled representation of obj to the open file object file. This is equivalent to 
Pickler(file, protocol, bin).dump(obj).

So to pickle newdic you should say
  cPickle.dump(newdic, write)
write.close()
but it 'overwrites' the saved dic. can you rw in one go, dump and load the
updated dict instantly??
I think you want to overwrite the saved dict, but with the new dict instead 
of with a filename string...
Kent
sending this in gmane mail2news gateway.
Thank you

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Re: Fw: Please submit to tutor list: dictionary update prob

2005-01-20 Thread Eri Mendz
Kent Johnson  tds.net> writes:

> 
> Jacob S. wrote:
> >> sorry to send this to you but if you may, kindly send to tutor list as im
> >> no longer subscribed.  my problem is in the update dict portion: it just
> >> doesnt update regardless how many contacts i add. kindly advise where
> >> my mistake is or code gone wrong. the rest of the options i will do on my
> >> own so just hold off the helps for now. appreciate all your good help.
> 
> >> def update_dict(d, f):
> >>''' update the saved dictionary file '''
> >>
> >>read = open(f, 'rb')
> >>newdic = cPickle.load(read)
> >>newdic.update(d)
> >>read.close()
> 
> You don't do anything with newdic. My guess is you want to dump it back to the
file so it is saved.
> 

this is what i tried:
read = open(f, 'rb')
newdic = cPickle.load(read)
newdic.update(d)
read.close()

write = open(f, 'wb')
cPickle.dump(f, write)
write.close()

but it 'overwrites' the saved dic. can you rw in one go, dump and load the
updated dict instantly??

sending this in gmane mail2news gateway.

-- 
regards,
erimendz






___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] RE:

2005-01-18 Thread Orri Ganel
Title: RE: 




Gopinath V, ASDC Chennai wrote:

  
  
  
  On Wed, 12 Jan 2005, Orri Ganel wrote:
  
  >  >>> stuff = [[0,'sdfsd','wrtew'],
[1, 'rht','erterg']]
  
  >  >>> stuff
  
  > [[0, 'sdfsd', 'wrtew'], [1, 'rht', 'erterg']]
  
  >  >>> print [stuff[i][0] for i in
range(len(stuff))]
  
  > [0, 1]
  
  
  Hi Orri,
  
  An alternative way to write this is:
  
  ###
  
  print [row[0] for row in stuff]
  
  ###
  
  which extracts the first element out of every "row"
sublist in 'stuff'.
  
  
  Best of wishes!
  
  
     This is fine.i just want to know if row is a
reserve word ?
  
  or is it a built in function 
  
   in IDLe environment .. the word row is not
highlighted ,what data type is (row) 
  
  

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor
  

That'll teach me to read the whole question.  In the above list
comprehension, stuff is the defined list.  row is
a variable created by the list comprehension.  Basically, this is
another way of saying:

for row in stuff:
    print row[0]

or

for i in range(len(stuff)):
    print stuff[i][0]

In this case, row's type is whatever type that element in stuff
is (which is a list). Ie:

>>> stuff = [[0,'sdfsd','wrtew'], [1, 'rht','erterg']]
>>> print [(row[0], type(row), type(row[0])) for row in stuff]
[(0, , ), (1, ,
)]
-- 
Email: singingxduck AT gmail DOT com
AIM: singingxduck
Programming Python for the fun of it.


___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] RE:

2005-01-18 Thread Orri Ganel
Title: RE: 




Gopinath V, ASDC Chennai wrote:

  
  
  
  On Wed, 12 Jan 2005, Orri Ganel wrote:
  
  >  >>> stuff = [[0,'sdfsd','wrtew'],
[1, 'rht','erterg']]
  
  >  >>> stuff
  
  > [[0, 'sdfsd', 'wrtew'], [1, 'rht', 'erterg']]
  
  >  >>> print [stuff[i][0] for i in
range(len(stuff))]
  
  > [0, 1]
  
  
  Hi Orri,
  
  An alternative way to write this is:
  
  ###
  
  print [row[0] for row in stuff]
  
  ###
  
  which extracts the first element out of every "row"
sublist in 'stuff'.
  
  
  Best of wishes!
  
  
     This is fine.i just want to know if row is a
reserve word ?
  
  or is it a built in function 
  
   in IDLe environment .. the word row is not
highlighted ,what data type is (row) 
  
  

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor
  

>>> row

Traceback (most recent call last):
  File "", line 1, in -toplevel-
    row
NameError: name 'row' is not defined
>>> import row

Traceback (most recent call last):
  File "", line 1, in -toplevel-
    import row
ImportError: No module named row

Looks like its not a reserved word.

-- 
Email: singingxduck AT gmail DOT com
AIM: singingxduck
Programming Python for the fun of it.


___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] RE:

2005-01-17 Thread Danny Yoo


> >  >>> stuff = [[0,'sdfsd','wrtew'], [1, 'rht','erterg']]
> >  >>> stuff
> > [[0, 'sdfsd', 'wrtew'], [1, 'rht', 'erterg']]
> >  >>> print [stuff[i][0] for i in range(len(stuff))]
> > [0, 1]
> >
> > An alternative way to write this is:
> >
> > ###
> > print [row[0] for row in stuff]
> > ###
> >
> > which extracts the first element out of every "row" sublist in
> > 'stuff'.


> This is fine.  I just want to know if row is a reserve word? or is it a
> built in function in IDLE environment.  The word row is not highlighted.
> What data type is (row)?


Hello!

When we have 'stuff' like this:

###
>>> stuff = [[0,'sdfsd','wrtew'], [1, 'rht','erterg']]
###

then we can ask for an element out of 'stuff'.  One thing we can do is
variable assignment:

###
>>> row = stuff[0]
###

'row' here is just an arbitrarily chosen variable name.  We can see that
"row"'s value is one of the sublists in 'stuff' by trying:

###
>>> print row
[0, 'sdfsd', 'wrtew']
###


We can also use a 'for' loop to march --- to "iterate" --- across a list:

###
>>> for row in stuff:
... print row, "is another element in 'stuff'"
...
[0, 'sdfsd', 'wrtew'] is another element in 'stuff'
[1, 'rht', 'erterg'] is another element in 'stuff'
###

'row' here is also used as a temporary variable name.  In a 'for' loop, it
is assigned to each element, as we repeat the loop's body.


If you have more questions, please feel free to ask.

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] RE:

2005-01-17 Thread Gopinath V, ASDC Chennai
Title: RE: 





On Wed, 12 Jan 2005, Orri Ganel wrote:


>  >>> stuff = [[0,'sdfsd','wrtew'], [1, 'rht','erterg']]
>  >>> stuff
> [[0, 'sdfsd', 'wrtew'], [1, 'rht', 'erterg']]
>  >>> print [stuff[i][0] for i in range(len(stuff))]
> [0, 1]



Hi Orri,


An alternative way to write this is:


###
print [row[0] for row in stuff]
###


which extracts the first element out of every "row" sublist in 'stuff'.



Best of wishes!



   This is fine.i just want to know if row is a reserve word ?
or is it a built in function 
 in IDLe environment .. the word row is not highlighted ,what data type is (row) 



___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Re: Is Tkinter the Gui in python

2005-01-14 Thread Alan Gauld
> Well... there's also Tix... but I don't know if you consider it as
> part of Tk or not.
>
> It's a bit complicated to get the feel from due to a lack of
explicit
> documentation for python, but once you get the tric about the
> Tcl->Python conversion, things get pretty smooth.

The Tcl-Python conversion isn't a problem, I use the O'Reilly
"Tcl/Tk in a Nutshell" that for standard Tkinter anyway.
But the Python WegaWidgets is probably the first port of call
for extensions to Tkinter. Tix would be my third option.
But in practice I've never even used PMW!

Alan G.

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Re: Is Tkinter the Gui in python

2005-01-13 Thread Liam Clarke
On Fri, 14 Jan 2005 09:51:48 +0900, Guillermo Fernandez Castellanos
<[EMAIL PROTECTED]> wrote:
> > > So tkinter is a good module to use if you only want simple widgets,
> > > but be prepared to switch to something newer when you hit it's
> > limitations.
> > This I agree with totally, fortunately I've yet to hit itslimitations
> > in my fairly simple GUIs.
> Well... there's also Tix... but I don't know if you consider it as
> part of Tk or not.
> 
> It's a bit complicated to get the feel from due to a lack of explicit
> documentation for python, but once you get the tric about the
> Tcl->Python conversion, things get pretty smooth.


Spectix is pretty usable.
-- 
'There is only one basic human right, and that is to do as you damn well please.
And with it comes the only basic human duty, to take the consequences.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Re: communication between java and python?

2005-01-13 Thread Jeff Shannon
Lee Harr wrote:
I'm trying to communicate between Python and Java and using
os.popen(). But thing dont work...The Java program reads strings from
stdin and the python program just writes to stdout.
[...]
"""
popen(command[, mode[, bufsize]])
Open a pipe to or from command. The return value is an open file
object connected to the pipe, which can be read or written
depending on whether mode is 'r' (default) or 'w'.
"""
So, I do not believe that you can both write to and read from
a file handle opened with popen.
Not only that, but access to the file-like pipe objects is probably 
buffered.  You'll want to call pipe.flush() after writing to it, or 
the child process won't actually see what you've written.

Jeff Shannon
Technician/Programmer
Credit International
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Re: Is Tkinter the Gui in python

2005-01-13 Thread Guillermo Fernandez Castellanos
> > So tkinter is a good module to use if you only want simple widgets,
> > but be prepared to switch to something newer when you hit it's
> limitations.
> This I agree with totally, fortunately I've yet to hit itslimitations
> in my fairly simple GUIs.
Well... there's also Tix... but I don't know if you consider it as
part of Tk or not.

It's a bit complicated to get the feel from due to a lack of explicit
documentation for python, but once you get the tric about the
Tcl->Python conversion, things get pretty smooth.

G
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Re: communication between java and python?

2005-01-13 Thread Lee Harr
I'm trying to communicate between Python and Java and using
os.popen(). But thing dont work...The Java program reads strings from
stdin and the python program just writes to stdout.
-first call the java program using:
handlers = os.popen('java StdIn)
-then:
handlers[0].write('string')
-and:
return_value_from_java = 
handlers[1].read()


From the docs on popen:
"""
popen(command[, mode[, bufsize]])
Open a pipe to or from command. The return value is an open file
object connected to the pipe, which can be read or written
depending on whether mode is 'r' (default) or 'w'.
"""
So, I do not believe that you can both write to and read from
a file handle opened with popen.
Check the docs for popen2 and see if that does what you want.
_
Express yourself instantly with MSN Messenger! Download today it's FREE! 
http://messenger.msn.click-url.com/go/onm00200471ave/direct/01/

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Re: Is Tkinter the Gui in python

2005-01-13 Thread Alan Gauld
> cross-platform gui that can be used on as many platforms as
possible,
> then use tkinter. As far as I know, tkinter isn't really developed
nowdays.

I assume Tkinter is tracking Tk and Tk is certainly still being
developed.
A new version was released quite recently I believe.

> So tkinter is a good module to use if you only want simple widgets,
> but be prepared to switch to something newer when you hit it's
limitations.

This I agree with totally, fortunately I've yet to hit itslimitations
in my fairly simple GUIs.

Alan G.

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Re: Is Tkinter the Gui in python

2005-01-13 Thread Abel Daniel
"Gopinath V, ASDC Chennai" writes:

>   Hi
> Is the standard Tkinter module in python does the GUI - Front -end
> Interface for Python

Well, if you mean "standard" as in included by default, then
yes. Tkinter however is a sort-of outdated gui. If you only want some
basic widgets, like entry boxes, buttons and such, and need to make a
cross-platform gui that can be used on as many platforms as possible,
then use tkinter. As far as I know, tkinter isn't really developed nowdays.

For more complicated guis, for example using tree widgets, you might be
better of with say, pygtk. However, pygtk afaict isn't available on as
many platforms as tkinter.

So tkinter is a good module to use if you only want simple widgets,
but be prepared to switch to something newer when you hit it's limitations.

-- 
Abel Daniel
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Re: My best GUI app so far.

2005-01-11 Thread Jonathan Hayward
Jacob S wrote.
I try to avoid using eval() wherever possible, which is almost
everywhere.  ;)   There's a huge security hole in using eval() on
arbitrary strings, and it's not the greatest performance either.
(Each invocation of eval() will generate bytecode and create a code
object that does essentially the same thing as my explicit conversion
code does, so by doing it manually you save a parsing/compiling step.)
  You're not eval()ing arbitrary strings here, at least, but it's
still good practice to only use eval() when absolutely necessary.
So, then, are you of the camp that believes that "a necessary eval() is 
still an eval()"? Quite a lot of good philosophers would agree with you!

--
++ Jonathan Hayward, [EMAIL PROTECTED]
** To see an award-winning website with stories, essays, artwork,
** games, and a four-dimensional maze, why not visit my home page?
** All of this is waiting for you at http://JonathansCorner.com
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Re: Tutor Digest, Vol 11, Issue 29

2005-01-09 Thread Jim Kelly
i had the same probblem with xp.

on mac os x i can double click on the file and it will
open.


xp opens the python file and closes it immediately
apon double click


open the python file via the Start Menu in xp.


Then hit f5 and the script will run


jk
nj
--- [EMAIL PROTECTED] wrote:

> Send Tutor mailing list submissions to
>   tutor@python.org
> 
> To subscribe or unsubscribe via the World Wide Web,
> visit
>   http://mail.python.org/mailman/listinfo/tutor
> or, via email, send a message with subject or body
> 'help' to
>   [EMAIL PROTECTED]
> 
> You can reach the person managing the list at
>   [EMAIL PROTECTED]
> 
> When replying, please edit your Subject line so it
> is more specific
> than "Re: Contents of Tutor digest..."
> 
> 
> Today's Topics:
> 
>1. Re: (no subject) (Alan Gauld)
>2. Crossword program (David Holland)
> 
> 
>
--
> 
> Message: 1
> Date: Sun, 9 Jan 2005 15:33:28 -
> From: "Alan Gauld" <[EMAIL PROTECTED]>
> Subject: Re: [Tutor] (no subject)
> To: "Jeffrey Thomas Peery" <[EMAIL PROTECTED]>,
> 
> Message-ID: <[EMAIL PROTECTED]>
> Content-Type: text/plain; charset="iso-8859-1"
> 
> 
> > Hello I can't seem to get the IDLE to start up in
> my windows XP by
> clicking
> > ...
> > Also I can't seem to get xp to recognize .py files
> belonging to
> python.
> 
> This is all fixable but it suggests maybe other
> problems in the
> installation. Personally I'd recommend reinstalling
> Python
> and that should fix all the problems.
> 
> Alan G.
> 
> 
> 
> --
> 
> Message: 2
> Date: Sun, 9 Jan 2005 21:44:03 + (GMT)
> From: David Holland <[EMAIL PROTECTED]>
> Subject: [Tutor] Crossword program
> To: tutor@python.org
> Message-ID:
>
<[EMAIL PROTECTED]>
> Content-Type: text/plain; charset=iso-8859-1
> 
> I wrote a program to create crosswords in python.
> It is not perfect but it works, is there any open
> source place I can put this for it to be used by
> anyone who wants it ?  (Subject to the gpl licence).
> Here is the code in case anyone is interested.
> 
> from Tkinter import *
> #Crossword program David Holland
> class Crossword(Frame):
> 
> def __init__(self, master):
> '''Default arguments'''
> Frame.__init__(self, master)
> self.grid()
> self.create_widgets()
> NUM_SQUARES = 169
> EMPTY = " "
> global questionanswer
> questionanswer = {}
> global dictshort
> dictshort = {}
> 
> def readdict(self):
> #get the dictionary from a file
> try:
> pickle_file = open(dictfile, "rb")
> dictread = cPickle.load(pickle_file)
> except:
> dictread = {}
> return dictread
> 
> def writedict(self, dictent):
> #write dictionary to file
> pickle_file = open(dictfile, "wb")
> cPickle.dump(dictent, pickle_file)
> pickle_file.close()
> 
> def showclues(self):
> #show clues on the screen
> questionanswer = self.readdict()
> textent = self.showinfo(questionanswer)
> #textent = questionanswer
> self.putinfo(textent)
> 
> def showinfo(self, dictent):
> #make the clues look readable
> i = 0
> listkeys = dictent.keys()
> #listkeys = listkeys.sort()
> textdisp = ''
> for item in listkeys:
> i = i+1
> istr = str(i) + " "
> question = dictent[item]
> textdisp = textdisp + istr + " the
> question is " + question + " the answer is " + item
> +
> "\n"
> return textdisp
> 
> def newcrosswordboard(self):
> #create a crossword board
> board = []
> for square in range (NUM_SQUARES):
> board.append(EMPTY)
> return board
> 
> #def newcrosswordboard(self):
> ##this is create a board with the numbers
> #board = []
> #for square in range (NUM_SQUARES):
> #text = str(square)
> #board.append(text)
> #return board
> 
> def deleteclue(self):
> #delete a clue
> try:
> numberentered = self.delete_ent.get()
> dictent = self.readdict()
> numberentered = int(numberentered)
> listkeys = dictent.keys()
> i = 1
> clue = ''
> for item in listkeys:
> if numberentered == i:
> del dictent[item]
> clue = item
> break
> i = i +1
> text = "Clue " + clue + " has been
> removed
> the list of clues now is :-" + "\n"
> self.writedict(dictent)
> moretext = self.showinfo(dictent)
> text = text + moretext
> except:
> text = "Please enter a number as a
> figure"
> self.putinfo(text)
> 
>   

[Tutor] Re: Tutor Digest, Vol 11, Issue 30

2005-01-09 Thread Jim Kelly
This script did not run properly


jk
nj
--- [EMAIL PROTECTED] wrote:

> Send Tutor mailing list submissions to
>   tutor@python.org
> 
> To subscribe or unsubscribe via the World Wide Web,
> visit
>   http://mail.python.org/mailman/listinfo/tutor
> or, via email, send a message with subject or body
> 'help' to
>   [EMAIL PROTECTED]
> 
> You can reach the person managing the list at
>   [EMAIL PROTECTED]
> 
> When replying, please edit your Subject line so it
> is more specific
> than "Re: Contents of Tutor digest..."
> 
> 
> Today's Topics:
> 
>1. Re: Crossword program (Alan Gauld)
> 
> 
>
--
> 
> Message: 1
> Date: Sun, 9 Jan 2005 22:07:31 -
> From: "Alan Gauld" <[EMAIL PROTECTED]>
> Subject: Re: [Tutor] Crossword program
> To: "David Holland" <[EMAIL PROTECTED]>,
> 
> Message-ID: <[EMAIL PROTECTED]>
> Content-Type: text/plain; charset="iso-8859-1"
> 
> Hi David,
> 
> Its probably the kind of thing you could put on the
> Useless Python website. Useless is a collection of
> not-too-serious software written in Python which,
> despite the name, is actually quite useful for
> beginners
> to download and look at and learn. They can try
> improving it, or using the ideas for their own
> programs.
> 
> But you might well get some suggestions on tidying
> it up a little first...
> 
> Alan G.
> 
> - Original Message - 
> From: "David Holland" <[EMAIL PROTECTED]>
> To: 
> Sent: Sunday, January 09, 2005 9:44 PM
> Subject: [Tutor] Crossword program
> 
> 
> > I wrote a program to create crosswords in python.
> > It is not perfect but it works, is there any open
> > source place I can put this for it to be used by
> > anyone who wants it ?  (Subject to the gpl
> licence).
> > Here is the code in case anyone is interested.
> >
> > from Tkinter import *
> > #Crossword program David Holland
> > class Crossword(Frame):
> >
> > def __init__(self, master):
> > '''Default arguments'''
> > Frame.__init__(self, master)
> > self.grid()
> > self.create_widgets()
> > NUM_SQUARES = 169
> > EMPTY = " "
> > global questionanswer
> > questionanswer = {}
> > global dictshort
> > dictshort = {}
> >
> > def readdict(self):
> > #get the dictionary from a file
> > try:
> > pickle_file = open(dictfile, "rb")
> > dictread = cPickle.load(pickle_file)
> > except:
> > dictread = {}
> > return dictread
> >
> > def writedict(self, dictent):
> > #write dictionary to file
> > pickle_file = open(dictfile, "wb")
> > cPickle.dump(dictent, pickle_file)
> > pickle_file.close()
> >
> > def showclues(self):
> > #show clues on the screen
> > questionanswer = self.readdict()
> > textent = self.showinfo(questionanswer)
> > #textent = questionanswer
> > self.putinfo(textent)
> >
> > def showinfo(self, dictent):
> > #make the clues look readable
> > i = 0
> > listkeys = dictent.keys()
> > #listkeys = listkeys.sort()
> > textdisp = ''
> > for item in listkeys:
> > i = i+1
> > istr = str(i) + " "
> > question = dictent[item]
> > textdisp = textdisp + istr + " the
> > question is " + question + " the answer is " +
> item +
> > "\n"
> > return textdisp
> >
> > def newcrosswordboard(self):
> > #create a crossword board
> > board = []
> > for square in range (NUM_SQUARES):
> > board.append(EMPTY)
> > return board
> >
> > #def newcrosswordboard(self):
> > ##this is create a board with the numbers
> > #board = []
> > #for square in range (NUM_SQUARES):
> > #text = str(square)
> > #board.append(text)
> > #return board
> >
> > def deleteclue(self):
> > #delete a clue
> > try:
> > numberentered = self.delete_ent.get()
> > dictent = self.readdict()
> > numberentered = int(numberentered)
> > listkeys = dictent.keys()
> > i = 1
> > clue = ''
> > for item in listkeys:
> > if numberentered == i:
> > del dictent[item]
> > clue = item
> > break
> > i = i +1
> > text = "Clue " + clue + " has been
> removed
> > the list of clues now is :-" + "\n"
> > self.writedict(dictent)
> > moretext = self.showinfo(dictent)
> > text = text + moretext
> > except:
> > text = "Please enter a number as a
> figure"
> > self.putinfo(text)
> >
> > def create_widgets(self):
> > #create GUI
> > self.question_lbl = Label(self, text =
> "Enter
> > the question ")
> >

Re: [Tutor] Re: The Game of Life

2005-01-06 Thread Kent Johnson
Brian van den Broek wrote:
In an earlier version, instead of the run_world() method I now have, I
put the following within my class definition and after (i.e. outside of)
the method defs:
.>while self.current_generation > self.total_generations:
.>time.sleep(self.sleep_interval)
.>self.update_world()
.>self.print_world()
which caused this:
Traceback (most recent call last):
   File "D:\Python Files\foogame_of_life.py", line 3, in -toplevel-
 class life_world:
   File "D:\Python Files\foogame_of_life.py", line 76, in life_world
 while self.current_generation > self.total_generations:
NameError: name 'self' is not defined
That surprised me -- I'd have guessed that within a class, self was
everywhere defined, and not just within methods.
self is just another method parameter. OK not quite, but it is a method parameter and it is only 
bound within the scope of the method. There is nothing magic about the name, either; it is just a 
(strong) convention.

In fact, by using a different name for self and the magic of lexical scoping and closures, you can 
do something very much like Java inner classes - make a nested class that has access to all the 
attributes of the enclosing class.

This is off-topic and a bit twisted, but I'm not going to let that stop me:
''' Make a nested class that has access to the attributes of its parent class 
'''
class Outer:
def __init__(outerSelf, x):
outerSelf.x = x
def makeNested(outerSelf, x):
class Nested:
def __init__(innerSelf, x):
innerSelf.x = x
def showX(innerSelf):
print 'outer x is', outerSelf.x
print 'inner x is', innerSelf.x
return Nested(x)
o = Outer(3)
n = o.makeNested(5)
n.showX()
o.x = 22
n.showX()

prints:
outer x is 3
inner x is 5
outer x is 22
inner x is 5
Kent
Clearly, I'm confused about something.
Anyway, thanks for reading. Best to all,
Brian vdB

# pylife.py
# Version 0.1
# Brian van den Broek
# [EMAIL PROTECTED]
# 2005-01-06 Thursday 17:41
# Copyright 2005
'''An OOP and ASCII based representation of Conway's Game of Life.
Much of the code was inspired by a post of Danny Yoo's on 2005-01-03 04:11
to the Python Tutor List. (You can find that post by searching the archives at
.)
I make no claims to ellegance or efficency -- this is only the second OOP I
have written.'''
import random, time
class life_world:

def __init__(self, X, Y, sleep_interval = 0.5, total_generations = 20):
self.X = X
self.Y = Y
self.world = self.seed_world()
self.sleep_interval = sleep_interval
self.total_generations = total_generations
self.current_generation = 0
self.print_world()

def seed_world(self):
'''Constructs a new random world of size XxY.'''

world = {}
for j in range(self.X):
for i in range(self.Y):
world[i, j] = random.choice((True, False))
return world
def print_world(self):
'''Prints out a string representation of a world.'''
print '\n\nGeneration Number: %s\n' %self.current_generation
print '--'*(self.Y + 1) + '-'
for j in range(self.X):
print '|',
for i in range(self.Y):
if self.world[i, j]:
print 'X',
else:
print ' ',
print '|'
print '--'*(self.Y + 1) + '-'

def count_neighbours(self, cell):
'''Returns the number of live neighbours to this one.

'neghboUrs because I'm Canadian, eh.
'''
live_count = 0
i,j = cell
for i_delta in [-1, 0, 1]:
for j_delta in [-1, 0, 1]:
if (i_delta, j_delta) == (0, 0):
continue
try:
# To deal with the edges of the matrix, where the
# deltas can take us out of bounds.
if self.world[i+i_delta, j+j_delta]:
live_count += 1
except KeyError:
pass
return live_count
def cell_will_change(self, cell):
'''Returns True if a cell will change, False otherwise.'''
change = False
if self.world[cell] and not self.count_neighbours(cell) in (2,3):
change = True
if not self.world[cell] and self.count_neighbours(cell) == 3:
change = True
return change
def get_changed_cells_list(self):
'''Returns a list of cells that will change in the next generation.'''
changed_cells_list = []
for c in self.world:
if self.cell_will_change(c):
changed_cells_list.append(c)
return changed_cells_list
def update_world(self):
'''Produces the n

[Tutor] Re: The Game of Life

2005-01-06 Thread Brian van den Broek
Hi all,
after making the sketch I posted a bit ago, I tried to turn to actual
work. But, the bug had bit. ;-) So, here is an attempt at filling out
that sketch in an OOP way. (It is my second OOP program, so if anyone
was so inclined, I'd very much appreciate any comments. Also, I have a 
question about a snag I ran into while debugging.)

I'm also not too used to sharing complete code. I'd put it in the public
domain, but since so much of it was derived from Danny's code, I don't
really know the conventions for so doing. (Were I to know it
appropriate, I'd follow the copyright comment line with:
# This software is released into the public domain.
# Fold, spindle, or mutilate at will
I've attached it rather than pasted it, as with something >100 lines I
don't feel up to shortening line for email. Sorry 'bout that.
The question:
In an earlier version, instead of the run_world() method I now have, I
put the following within my class definition and after (i.e. outside of)
the method defs:
.>while self.current_generation > self.total_generations:
.>time.sleep(self.sleep_interval)
.>self.update_world()
.>self.print_world()
which caused this:
Traceback (most recent call last):
   File "D:\Python Files\foogame_of_life.py", line 3, in -toplevel-
 class life_world:
   File "D:\Python Files\foogame_of_life.py", line 76, in life_world
 while self.current_generation > self.total_generations:
NameError: name 'self' is not defined
That surprised me -- I'd have guessed that within a class, self was
everywhere defined, and not just within methods.
Clearly, I'm confused about something.
Anyway, thanks for reading. Best to all,
Brian vdB
# pylife.py
# Version 0.1
# Brian van den Broek
# [EMAIL PROTECTED]
# 2005-01-06 Thursday 17:41
# Copyright 2005

'''An OOP and ASCII based representation of Conway's Game of Life.
Much of the code was inspired by a post of Danny Yoo's on 2005-01-03 04:11
to the Python Tutor List. (You can find that post by searching the archives at
.)

I make no claims to ellegance or efficency -- this is only the second OOP I
have written.'''

import random, time

class life_world:

def __init__(self, X, Y, sleep_interval = 0.5, total_generations = 20):
self.X = X
self.Y = Y
self.world = self.seed_world()
self.sleep_interval = sleep_interval
self.total_generations = total_generations
self.current_generation = 0
self.print_world()

def seed_world(self):
'''Constructs a new random world of size XxY.'''

world = {}
for j in range(self.X):
for i in range(self.Y):
world[i, j] = random.choice((True, False))
return world

def print_world(self):
'''Prints out a string representation of a world.'''

print '\n\nGeneration Number: %s\n' %self.current_generation
print '--'*(self.Y + 1) + '-'
for j in range(self.X):
print '|',
for i in range(self.Y):
if self.world[i, j]:
print 'X',
else:
print ' ',
print '|'
print '--'*(self.Y + 1) + '-'

def count_neighbours(self, cell):
'''Returns the number of live neighbours to this one.

'neghboUrs because I'm Canadian, eh.
'''
live_count = 0
i,j = cell
for i_delta in [-1, 0, 1]:
for j_delta in [-1, 0, 1]:
if (i_delta, j_delta) == (0, 0):
continue
try:
# To deal with the edges of the matrix, where the
# deltas can take us out of bounds.
if self.world[i+i_delta, j+j_delta]:
live_count += 1
except KeyError:
pass
return live_count

def cell_will_change(self, cell):
'''Returns True if a cell will change, False otherwise.'''
change = False
if self.world[cell] and not self.count_neighbours(cell) in (2,3):
change = True
if not self.world[cell] and self.count_neighbours(cell) == 3:
change = True
return change

def get_changed_cells_list(self):
'''Returns a list of cells that will change in the next generation.'''

changed_cells_list = []
for c in self.world:
if self.cell_will_change(c):
changed_cells_list.append(c)
return changed_cells_list

def update_world(self):
'''Produces the next generation world.'''
self.current_generation += 1
changed_cells_list = self.get_changed_cells_list()
for c in changed_cells_list:
self.world[c] = not self.world[c]

def run_world(self):
while self.current_generation < self.total_generations:
time.sleep(self.sleep_interval)
self.upd

Re: [Tutor] Re: The Game of Life

2005-01-06 Thread Max Noel
On Jan 6, 2005, at 21:20, Brian van den Broek wrote:
Oh, the Life rules allow a world where every cell will change in 
the next generation, iff your world is a torus (i.e. the lower row 
"touches" the upper row as if it were immediately above it, and the 
right column "touches" the left column as if it were immediately left 
of it). It is quite trivial: set all cells to LIVE. Next generation 
they're all DEAD.
Topologist! (That's cheating!) ;-)
If we are going that way, you 'iff' seems a bit hasty. Take the 1x1 
matrix 'full' of live cells.
	Well, if the only cell of a 1x1 torus matrix is LIVE, that  means it 
is surrounded by 4 LIVE cells, doesn't it? :D

Also, other 'funny' (in the sense that a torus is funny) planes could 
be defined (say a torus-like structure with more than 1 whole -- 
cannot recall the general terminology from ill-remembered topology), 
etc. I meant the claim for a standard non-trivial (i.e. M > 1 and N > 
1) MxN euclidean plane matrix, but your correction is both amusing and 
welcome.
	Thanks :)
	However, the main reason why I talked about a torus is that it's one 
of the two obvious choices when you're implementing Life using a 2D 
matrix (the other being a finite rectangular plane).

-- Max
maxnoel_fr at yahoo dot fr -- ICQ #85274019
"Look at you hacker... A pathetic creature of meat and bone, panting 
and sweating as you run through my corridors... How can you challenge a 
perfect, immortal machine?"

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Re: The Game of Life

2005-01-06 Thread Brian van den Broek
Max Noel said unto the world upon 2005-01-06 15:39:

On Jan 6, 2005, at 20:05, Brian van den Broek wrote:

I gave some thought (though produced no code) to the question of how 
to do a life game before you [Danny] posted your code. My naive approach 
differs a bit, and it seems to me better. I'd like to know why I am 
wrong ;-)

So, relying on your [Danny's] code unless differences specified (and, like you, 
not making it OOP, so having more passing of the world than I'd like, 
but I'm only just now groking the OOP way), I would have done 
something like the following. (Please be tolerant of any syntactic 
slips; I think and hope my aim is clear, if not the execution.):

1) Define world by filling an M by N matrix with True and False. 
Otherwise, as your step (1).

2) Define a print function which goes through the matrix, printing one 
thing for each True cell and another for each False cell.

3) Define the count_live_neighbours() roughly as you did. (The actual 
code below assumes your count function, modulo the change to it that 
you define a LIVE name and I am just using True.)

4) Define a "will be changed function" roughly as the untested code:


5) Define a get_changed_cells_list function (again, untested):


6) Define update_world function (again, untested):

I hope the fragmentary nature of this makes my intent clear.
Anyway, as I see it, this has the following advantages over your 
posted code:

1) Cell representations done with built-ins seems likely to be 
quicker. (A minor point, though.)

2) Use of booleans for cell contents makes the change cell procedure 
simply saying not
.> cell_contents  # as in for loop of my update_world().

3) Neither a copy of the world nor the design pattern is needed. 
Instead, I make a list of the cells to be changed. In the limit, where 
ever cell will change, this is no better than a copy of the world, but 
i) it often is better, and ii) I'm not sure the Life rules can create 
a world where every cell will change in the next generation, anyway.

I don't see any disadvantages, but then I don't see too well ;-)

You're wrong in that you're not wrong. I'm not very familiar with 
design patterns yet, but to me, what you just described looks like 
another Life implementation using the Command design pattern. It is, 
however, more efficient and IMO elegant than Danny's.
Well, thanks. :-)
Correct me if I'm wrong (I may be talking out of, er, a certain part 
of my anatomy that is far from my mouth), but the basic idea of the 
Command design pattern is to store the changes to be made (instead of 
the post-change states) in a disposable data structure, then to apply 
them to the original copy of the world. Which should be more efficient, 
at least memory-wise. Right?

I don't know design patterns beyond the concept and a teeny bit of 
poking about. I guess I should check, but I got the sense that the 
Command pattern involved storing actual instructions instead of 
representational data. (Ugly term, but since Python functions are 
first-class objects I need something for data that isn't an 
instruction.) The sense comes more from the name than anything else, though.

Oh, the Life rules allow a world where every cell will change in the 
next generation, iff your world is a torus (i.e. the lower row "touches" 
the upper row as if it were immediately above it, and the right column 
"touches" the left column as if it were immediately left of it). It is 
quite trivial: set all cells to LIVE. Next generation they're all DEAD.
Topologist! (That's cheating!) ;-)
If we are going that way, you 'iff' seems a bit hasty. Take the 1x1 
matrix 'full' of live cells. Also, other 'funny' (in the sense that a 
torus is funny) planes could be defined (say a torus-like structure with 
more than 1 whole -- cannot recall the general terminology from 
ill-remembered topology), etc. I meant the claim for a standard 
non-trivial (i.e. M > 1 and N > 1) MxN euclidean plane matrix, but your 
correction is both amusing and welcome.


Best to all,
Brian vdB
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Re: The Game of Life

2005-01-06 Thread Max Noel
	First of all, thanks for answering our questions, Danny! And sorry for 
the lag before my reply, but I was rather busy over the last few days 
(moving "back" to the UK).

On Jan 6, 2005, at 20:05, Brian van den Broek wrote:
I am having a hard time figuring out how to efficiently snip and 
comment, so please bear with any organizational issues. I think I will 
just preserve the parts relevant to what I want to talk/ask about and 
write at the end.
And I hereby massively SNIP whatever remained of it. :D
I gave some thought (though produced no code) to the question of how 
to do a life game before you posted your code. My naive approach 
differs a bit, and it seems to me better. I'd like to know why I am 
wrong ;-)

So, relying on your code unless differences specified (and, like you, 
not making it OOP, so having more passing of the world than I'd like, 
but I'm only just now groking the OOP way), I would have done 
something like the following. (Please be tolerant of any syntactic 
slips; I think and hope my aim is clear, if not the execution.):

1) Define world by filling an M by N matrix with True and False. 
Otherwise, as your step (1).

2) Define a print function which goes through the matrix, printing one 
thing for each True cell and another for each False cell.

3) Define the count_live_neighbours() roughly as you did. (The actual 
code below assumes your count function, modulo the change to it that 
you define a LIVE name and I am just using True.)

4) Define a "will be changed function" roughly as the untested code:

5) Define a get_changed_cells_list function (again, untested):

6) Define update_world function (again, untested):

I hope the fragmentary nature of this makes my intent clear.
Anyway, as I see it, this has the following advantages over your 
posted code:

1) Cell representations done with built-ins seems likely to be 
quicker. (A minor point, though.)

2) Use of booleans for cell contents makes the change cell procedure 
simply saying not
.> cell_contents  # as in for loop of my update_world().

3) Neither a copy of the world nor the design pattern is needed. 
Instead, I make a list of the cells to be changed. In the limit, where 
ever cell will change, this is no better than a copy of the world, but 
i) it often is better, and ii) I'm not sure the Life rules can create 
a world where every cell will change in the next generation, anyway.

I don't see any disadvantages, but then I don't see too well ;-)
	You're wrong in that you're not wrong. I'm not very familiar with 
design patterns yet, but to me, what you just described looks like 
another Life implementation using the Command design pattern. It is, 
however, more efficient and IMO elegant than Danny's.
	Correct me if I'm wrong (I may be talking out of, er, a certain part 
of my anatomy that is far from my mouth), but the basic idea of the 
Command design pattern is to store the changes to be made (instead of 
the post-change states) in a disposable data structure, then to apply 
them to the original copy of the world. Which should be more efficient, 
at least memory-wise. Right?

	Oh, the Life rules allow a world where every cell will change in the 
next generation, iff your world is a torus (i.e. the lower row 
"touches" the upper row as if it were immediately above it, and the 
right column "touches" the left column as if it were immediately left 
of it). It is quite trivial: set all cells to LIVE. Next generation 
they're all DEAD.
	If your world is a finite rectangle, I think the best you can get is a 
world where all but four cells (the corners) change next generation 
(same method). As your rectangle stretches to infinity, obviously, the 
cells changed/total cells ration converges toward 1.

In any case, your point still stands.
did you mean make the world a class (and thus avoid the sort of 
passing the world dict up and down as I did here?) Either way, a quick 
word or two will be great; I'm not asking for you to take the time to 
code it up for me :-)
Probably, but I don't think that's relevant.
-- Max
maxnoel_fr at yahoo dot fr -- ICQ #85274019
"Look at you hacker... A pathetic creature of meat and bone, panting 
and sweating as you run through my corridors... How can you challenge a 
perfect, immortal machine?"

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


<    1   2   3   4   5   6   >