Newbie question - better way to do this?

Steve Howell showell30 at yahoo.com
Sun May 27 10:41:35 EDT 2007


--- Eric <venner at gmail.com> wrote:

> I have some working code, but I realized it is just
> the way I would
> write it in C, which means there is probably a
> better (more pythonic)
> way of doing it.
> 
> Here's the section of code:
> 
>     accumulate = firstIsCaps = False
>     accumStart = i = 0
>     while i < len(words):
>         firstIsCaps = firstIsCapitalized(words[i])
>         if firstIsCaps and not accumulate:
>             accumStart, accumulate = i, True
>         elif accumulate and not firstIsCaps:
>             doSomething(words[accumStart : i])
>             accumulate = False
>         i += 1
> 
> words is a big long array of strings.  What I want
> to do is find
> consecutive sequences of words that have the first
> letter capitalized,
> and then call doSomething on them.  (And you can
> ignore the fact that
> it won't find a sequence at the very end of words,
> that is fine for my
> purposes).
> 

Try out this program:

def doSomething(stuff):
    print stuff

def firstIsCapitalized(word):
    return 'A' <= word[0] <= 'Z'

def orig_code(words):
    print 'C-style'
    accumulate = firstIsCaps = False
    accumStart = i = 0
    while i < len(words):
        firstIsCaps = firstIsCapitalized(words[i])
        if firstIsCaps and not accumulate:
            accumStart, accumulate = i, True
        elif accumulate and not firstIsCaps:
            doSomething(words[accumStart : i])
            accumulate = False
        i += 1

def another_way(words):
    print 'more idiomatic, with minor bug fix'
    group = []
    for word in words:
        if firstIsCapitalized(word):
            group.append(word)
        elif group:
            doSomething(group)
            group = []
    if group:
        doSomething(group)

orig_code(['foo', 'Python', 'Ruby', 'c', 'xxx',
'Perl'])
another_way(['foo', 'Python', 'Ruby', 'c', 'xxx',
'Perl'])

See also the groupby method in itertools.

http://docs.python.org/lib/itertools-functions.html




       
____________________________________________________________________________________Get the Yahoo! toolbar and be alerted to new email wherever you're surfing.
http://new.toolbar.yahoo.com/toolbar/features/mail/index.php



More information about the Python-list mailing list