Re: [Tutor] conditionals with slicing not seeming to work

2008-01-28 Thread Alan Gauld
"Rob Stevenson" <[EMAIL PROTECTED]> wrote

> I'm working at a certain website's puzzles using
> python in order to learn the language,

OK, Then I'll add some other comments

> the intention of this snippet is to only print slices where 
> character 1 is
> lower case, 2-4 and 6-8 are upper.  The logic here looks right to a 
> VB eye.

s="""kKjyaqbooOlNkAddgAazFlgKLjlXDGtlv
> etc...

> h = range(len(s)-9)
> for i in h:

more conventionally in python to just say

for i in range(len(s)-9)

>j=s[i:i+8]
>if j[0].islower():
>if j[1:3].isupper():
>  if j[5:7].isupper():

And this would reflect the problem statement better if
you used boolean logic

if j[0].islower() and j[1:4].isupper() and j[5:8].isupper():
print j

You could also do this using regular expressions if
you want an alternative approach.

HTH,

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld 


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


Re: [Tutor] replacing range with xrange

2008-01-28 Thread Tim Golden
Andy Cheesman wrote:
> Hi people,
> 
> After watching a nice Google video on Python 3K, and seeing the 
> forthcoming removal of range, I've looked at substitution range with 
> xrange within my code. Direct substitution works for 90% percent of the 
> case (i.e.   for thing in xrange(number):  ), however i can't change the 
> example below where I need a non-continuous range. Any suggestions?
> 
> Andy
> 
> x = range(10)  + range(20, 30)
> 
> for thing in x:
> ...

Define your own top-level range as:

def range (x):
   return list (xrange (x))

maybe?


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


[Tutor] replacing range with xrange

2008-01-28 Thread Andy Cheesman
Hi people,

After watching a nice Google video on Python 3K, and seeing the 
forthcoming removal of range, I've looked at substitution range with 
xrange within my code. Direct substitution works for 90% percent of the 
case (i.e.   for thing in xrange(number):  ), however i can't change the 
example below where I need a non-continuous range. Any suggestions?

Andy

x = range(10)  + range(20, 30)

for thing in x:
...

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


Re: [Tutor] conditionals with slicing not seeming to work

2008-01-28 Thread Ricardo Aráoz
Alan Gauld wrote:
> "Rob Stevenson" <[EMAIL PROTECTED]> wrote
> 
>> I'm working at a certain website's puzzles using
>> python in order to learn the language,
> 
> OK, Then I'll add some other comments
> 
>> the intention of this snippet is to only print slices where 
>> character 1 is
>> lower case, 2-4 and 6-8 are upper.  The logic here looks right to a 
>> VB eye.
> 
> s="""kKjyaqbooOlNkAddgAazFlgKLjlXDGtlv
>> etc...
> 
>> h = range(len(s)-9)
>> for i in h:
> 
> more conventionally in python to just say
> 
> for i in range(len(s)-9)
> 
>>j=s[i:i+8]
>>if j[0].islower():
>>if j[1:3].isupper():
>>  if j[5:7].isupper():
> 
> And this would reflect the problem statement better if
> you used boolean logic
> 
> if j[0].islower() and j[1:4].isupper() and j[5:8].isupper():
> print j
> 
> You could also do this using regular expressions if
> you want an alternative approach.
> 
> HTH,
> 

Maybe you are trying to pass python challenge #3? Better use re module
as Alan suggested, and remember, it's EXACTLY three on each side.

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


Re: [Tutor] replacing range with xrange

2008-01-28 Thread Kent Johnson
Andy Cheesman wrote:

> After watching a nice Google video on Python 3K, and seeing the 
> forthcoming removal of range, I've looked at substitution range with 
> xrange within my code. Direct substitution works for 90% percent of the 
> case (i.e.   for thing in xrange(number):  ), however i can't change the 
> example below where I need a non-continuous range. Any suggestions?
> 
> Andy
> 
> x = range(10)  + range(20, 30)

x = list(range(10)) + list(range(20, 30))

or

from itertools import chain
for thing in chain(range(10), range(20, 30)):

which avoids creating the intermediate lists.

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


Re: [Tutor] replacing range with xrange

2008-01-28 Thread bob gailer
Kent Johnson wrote:
> bob gailer wrote:
>
>   
>> I disagree based on PEP 3100 (http://www.python.org/dev/peps/pep-3100/)
>>
>> Built-in Namespace:
>> - Make built-ins return an iterator where appropriate (e.g. range(), 
>> zip(), map(), filter(), etc.)
>>
>> To be removed:
>> - xrange(): use range() instead
>> 
>
> Right, that's a good clarification.
>
> xrange() is being renamed to range(), so there will be no xrange() and 
> range() will return an iterator rather than a list.
>
> Hmm, does that mean that the arguments to range() will be restricted to 
> long integers?
>   
Well the same PEP says:

Atomic Types:
- Remove distinction between int and long types

-- 
Bob Gailer
919-636-4239 Chapel Hill, NC

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


Re: [Tutor] replacing range with xrange

2008-01-28 Thread bob gailer
Andy Cheesman wrote:
> Hi people,
>
> After watching a nice Google video on Python 3K, and seeing the 
> forthcoming removal of range, 
I disagree based on PEP 3100 (http://www.python.org/dev/peps/pep-3100/)

Built-in Namespace:
- Make built-ins return an iterator where appropriate (e.g. range(), 
zip(), map(), filter(), etc.)

To be removed:
- xrange(): use range() instead

-- 
Bob Gailer
919-636-4239 Chapel Hill, NC

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


Re: [Tutor] replacing range with xrange

2008-01-28 Thread Kent Johnson
bob gailer wrote:

> I disagree based on PEP 3100 (http://www.python.org/dev/peps/pep-3100/)
> 
> Built-in Namespace:
> - Make built-ins return an iterator where appropriate (e.g. range(), 
> zip(), map(), filter(), etc.)
> 
> To be removed:
> - xrange(): use range() instead

Right, that's a good clarification.

xrange() is being renamed to range(), so there will be no xrange() and 
range() will return an iterator rather than a list.

Hmm, does that mean that the arguments to range() will be restricted to 
long integers?

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


Re: [Tutor] replacing range with xrange

2008-01-28 Thread Alan Gauld
> xrange() is being renamed to range(), so there will be no xrange() 
> and
> range() will return an iterator rather than a list.

That's sad to see, I use range to generate lists of integers
almost as much as I use it for iteration. But maybe I'm
unusual in that respect, I do use Python mainly for
simulations and its ease of creating large test data
sets is one of its nicer features. Having to convert
an iterator into a list is a bit ugly IMHO! I'd have
preferred to see xrange kept as an iterator and range
returning a list. That seems to me more in keeping
with the names too.

Alan G. 


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


Re: [Tutor] replacing range with xrange

2008-01-28 Thread bob gailer
Alan Gauld wrote:
>> xrange() is being renamed to range(), so there will be no xrange() 
>> and
>> range() will return an iterator rather than a list.
>> 
>
> That's sad to see, I use range to generate lists of integers
> almost as much as I use it for iteration. But maybe I'm
> unusual in that respect, I do use Python mainly for
> simulations and its ease of creating large test data
> sets is one of its nicer features. Having to convert
> an iterator into a list is a bit ugly IMHO! I'd have
> preferred to see xrange kept as an iterator and range
> returning a list. That seems to me more in keeping
> with the names too.
>   
FWIW on my computer
l = range(3000) takes under 0.19 seconds
l = list(xrange(300)) under 0.27.
So I don't think performance is an issue.


-- 
Bob Gailer
919-636-4239 Chapel Hill, NC

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


Re: [Tutor] data structure question

2008-01-28 Thread Alexander
Thanks for all the responses. I'm using this both as an opportunity to
learn and to create something that does exactly what I want it to so
that's why I want to write my own program.

I decided to go with a flat list in the end. Now I have a working
implementation but it's not as nice as I think it could be. This is
what I need:

Each task has a set of attributes. Some of these attribute values have
an internal and an external value or representation (for example the
attribute deadline, which is a datetime internally and a formatted
string externally).

The list of tasks should be sortable, filterable, and searchable on
any of the attributes. This needs to be done on the internal
attributes. The list of tasks should also be easily displayed with the
attributes as formatted strings.

My attempt is pasted below. My question now is whether this is a
tenable implementation, what's wrong with it if not, and at which
point something like this is better done using a relational backend
with SQL. To me it seems like the operations that I want to be able to
do are more easily implemented in SQL (perhaps because I don't know
enough python...) but what are the drawbacks of such an approach?

The code:

#! /usr/bin/python
# vim: tabstop=4 expandtab shiftwidth=4
"""Flat implementation of tasklist."""

import cPickle as pickle
import datetime
import parsedatetime.parsedatetime

import pdb

class TaskList(object):
defaults = ['rgtd','backend','testing 1','tomorrow',1,'open']
def __init__(self):
"""Create an empty instance"""
self.tasks = []
self.modified = False

def addTask(self,args):
"""Add a task."""
args = args + self.defaults[len(args):]
task = Task(args)
self.tasks.append(task)
self.modified = True

def clear(self):
"""Delete all tasks."""
self.tasks = []
self.modified = True

def removeTask(self,index):
try:
task = self.tasks.pop(index)
self.modified = True
result = 'Removed task %i\t%s'  (index,task.__str__())
except:
result = 'Removing task %i failed.' % index
return result

def setStatus(self,index,status):
self.tasks[int(index)].status = str(status)
self.modified=True

def save(self, filename='.rgtddb'):
"""Save tasklist to file using pickle."""
file = open(filename,'wb')
pickle.dump(self,file)
file.close()
self.modified = False

def sorted(self,field='int_deadline',ascending=False):
"""Return tasks sorted on int_deadline.
Adapted from Python Cookbook 2ed Recipe 5.3.
"""
intermed = [ (getattr(x, field), i, x) for i, x in 
enumerate(self.tasks) ]
intermed.sort(reverse=ascending)
return [x[-1] for x in intermed]

def sort(self,field='int_deadline',ascending=False):
self.tasks[:] = self.sorted(field,ascending)

def output(self,displaymask=False):
row = ''

# Set displaymask to all fields in sortorder if no mask is 
supplied.
if not displaymask:
displaymask = 
['status','deadline','cost','project','area','task']

# Sort tasks
self.sort()

# Produce output string
for index, task in enumerate(self.tasks):
row = row + '%i\t%s\n' % (index, 
'\t'.join([getattr(task,field)for
field in displaymask]))
return row

class Task(object):
def __init__(self,args):
"""Set all task attributes from an argument list in correct 
order."""
self.project = args[0]
self.area = args[1]
self.task = args[2]
self.deadline = args[3]
self.cost = args[4]
self.status = args[5]

def setDeadline(self, value):
"""Use parsedatetime.parsedatetime to parse human-readable
deadline entry to a datetime object.
"""
parsedatetime.parsedatetime._debug=False
calendar = parsedatetime.parsedatetime.Calendar()
self.__deadline = 
datetime.datetime(*calendar.parse(value)[0][0:7])
# datetime object is also stored in for internal use (sorting)
self.int_deadline = 
datetime.datetime(*calendar.parse(value)[0][0:7])

def getDeadline(self):
"""Return deadline as a string in the format day-month."""
return self.__deadline.strftime('

[Tutor] What web framework?

2008-01-28 Thread Terry Carroll
I'm writing a pretty small database program.  It tracks CDROMs with
archives of, say, MP3 files; although I'm writing it with an eye to to
generalize to, for example, support a collection of image files, or actual 
audio CDs, as well; or just about any types of files that might lend 
themselves to being stored on CDROM in a consistently organized manner.

I've decided to split out the program(s) to add and delete data from the
querying.  Data will be added by reading a CDROM and processing all the
files; all the data going into the database is derived from the files
themselves, so there's no data entry.  Similarly, data will only be
deleted by deleting all rows that relate back to a particular volume; I'll 
probably do that with a separate program that does just that function.  
Neither of these is really worthy of a flashy GUI interface.

But querying's different.  I'd initially planed on making this a wxPython 
application, but I think it might be simpler to have it as a web app, even 
though I'll be the only user, and the db will be resident on the same 
program I'm querying from.

This calls for using a web framework, and I'm casting about for advice on 
which one to use.  This probably isn't the best-formed question, because I 
don't know what factors should influence a choice of framework.  Some 
factors that come to mind are:

- this application will be query-only; no updating, adding or deleting.
- the database is SQLite.
- security and authentication are not important; there's no private data 
  here, I'm the only user, and I'm firewalled. If a particular framework
  has security features, I'll use them, but I don't see them as important.
  (Famous last words.)

I'd like something that doesn't take forever to get up to speed on, but
that isn't short on features.  Although this is the only framework project
I see in the immediate future, I can imagine I might want to do another
project sometime in the future.  I really want to be framework-monogamous
here: I don't program for a living, and getting up to speed on a framework
seems like work to me.

It looks like the leading candidates here are Turbogears and Django.  
Turbogears looks kind of nice to me, but it looks like it's going through
some big changes right now.  Apparently, on the database side, SQLObject
is being replaced with SQLAlchemy, and on the templating side, Kid is
being replaced with Genshi.  I worry that a lot of the time put into 
learning TG in its present form will ultimately be time wasted.

Any thoughts on these two frameworks, or another that I might be 
overlooking?  Oh, since I don't know enough about frameworks to even know 
what factors are worth considering: what factors would I be considering?

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


Re: [Tutor] replacing range with xrange

2008-01-28 Thread Alan Gauld

"bob gailer" <[EMAIL PROTECTED]> wrote

>> That's sad to see, I use range to generate lists of integers
>> almost as much as I use it for iteration. 

> FWIW on my computer
> l = range(3000) takes under 0.19 seconds
> l = list(xrange(300)) under 0.27.
> So I don't think performance is an issue.

Performance was never an issue for me, its just that I think 
the explicit conversion to list looks ugly. After all a range is 
a range of numbers to my mind and a list (actually a tuple) 
seems like the sensible representation. Making it an iterator 
seems to be based on an assumption that range will 
primarily be used in a for loop.

Alan G

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


Re: [Tutor] What web framework?

2008-01-28 Thread Alan Gauld
"Terry Carroll" <[EMAIL PROTECTED]> wrote

> But querying's different.  I'd initially planed on making this a 
> wxPython
> application, but I think it might be simpler to have it as a web 
> app, even
> though I'll be the only user, and the db will be resident on the 
> same
> program I'm querying from.
>
> This calls for using a web framework,

Not really, a simple CGI app would be suffficient.
A framework is really only needed where you have lots of pages
all with the same look n feel and lots of interaction between them.
If all you need is a query screen and a results screen then basic
CGI should be more than adequate.

If you really want more then look at basic CherryPy rather than
TurboGears/Django. It takes the CGI pains away while keeping
the code simple and direct.

TurboGears and Django are both excellent but the learning curve
for a simple app is more than the gain IMHO. OTOH If you want
to build knowledge for the future then pick one and go with it.
It doesn't much matter which they all use the same principles
its only syntax differences really.

IMHO at least,

Alan G. 


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


Re: [Tutor] What web framework?

2008-01-28 Thread Kent Johnson
Terry Carroll wrote:
> Any thoughts on these two frameworks, or another that I might be 
> overlooking?  Oh, since I don't know enough about frameworks to even know 
> what factors are worth considering: what factors would I be considering?

TG and Django both work well, and both have many satisfied users. 
Personally I prefer Django, I am using it at work and like it a lot. My 
first impressions of both are here:
http://personalpages.tds.net/~kent37/blog/arch_m1_2007_02.html#e73

There are some lighter-weight frameworks you might consider as well, 
web.py anyway.

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