Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > Python > SimplePrograms challenge

Reply
Thread Tools

SimplePrograms challenge

 
 
Steve Howell
Guest
Posts: n/a
 
      06-11-2007
Hi, I'm offering a challenge to extend the following
page by one good example:

http://wiki.python.org/moin/SimplePrograms

Right now the page starts off with 15 examples that
cover lots of ground in Python, but they're still
scratching the surface. (There are also two Eight
Queens implementations, but I'm looking to fill the
gap in lines-of-code, and they're a little long now.)

I'm looking for a good 16-line code example with the
following qualities:

1) It introduces some important Python concept that
the first 15 programs don't cover.

2) It's not too esoteric. Python newbies are the
audience (but you can assume they're not new to
programming in general).

3) It runs on Python 2.4.

4) It doesn't just demonstrate a concept; it solves
a problem at face value. (It can solve a whimsical
problem, like counting rabbits, but the program itself
should be "complete" and "suitably simple" for the
problem at hand.)

5) You're willing to have your code reviewed by the
masses.

6) No major departures from PEP 8.

Any takers?

-- Steve







__________________________________________________ __________________________________
Looking for a deal? Find great prices on flights and hotels with Yahoo! FareChase.
http://farechase.yahoo.com/
 
Reply With Quote
 
 
 
 
infidel
Guest
Posts: n/a
 
      06-11-2007
# reading CSV files, tuple-unpacking
import csv

#pacific.csv contains:
#1,CA,California
#2,AK,Alaska
#3,OR,Oregon
#4,WA,Washington
#5,HI,Hawaii

reader = csv.reader(open('pacific.csv'))
for id, abbr, name in reader:
print '%s is abbreviated: "%s"' % (name, abbr)

 
Reply With Quote
 
 
 
 
=?iso-8859-1?B?QW5kcuk=?=
Guest
Posts: n/a
 
      06-11-2007
On Jun 11, 6:56 pm, Steve Howell <(E-Mail Removed)> wrote:
> Hi, I'm offering a challenge to extend the following
> page by one good example:
>
> http://wiki.python.org/moin/SimplePrograms
>
> Right now the page starts off with 15 examples that
> cover lots of ground in Python, but they're still
> scratching the surface. (There are also two Eight
> Queens implementations, but I'm looking to fill the
> gap in lines-of-code, and they're a little long now.)
>
> I'm looking for a good 16-line code example with the
> following qualities:
>
> 1) It introduces some important Python concept that
> the first 15 programs don't cover.
>
> 2) It's not too esoteric. Python newbies are the
> audience (but you can assume they're not new to
> programming in general).
>
> 3) It runs on Python 2.4.
>
> 4) It doesn't just demonstrate a concept; it solves
> a problem at face value. (It can solve a whimsical
> problem, like counting rabbits, but the program itself
> should be "complete" and "suitably simple" for the
> problem at hand.)
>
> 5) You're willing to have your code reviewed by the
> masses.
>
> 6) No major departures from PEP 8.
>
> Any takers?


Ok, doctest-based version of the Unit test example added; so much more
Pythonic

André

P.S. Congrats for starting this!

>
> -- Steve
>
> __________________________________________________ __________________________________
> Looking for a deal? Find great prices on flights and hotels with Yahoo! FareChase.http://farechase.yahoo.com/



 
Reply With Quote
 
John Machin
Guest
Posts: n/a
 
      06-11-2007
On Jun 12, 8:51 am, infidel <(E-Mail Removed)> wrote:
> # reading CSV files, tuple-unpacking
> import csv
>
> #pacific.csv contains:
> #1,CA,California
> #2,AK,Alaska
> #3,OR,Oregon
> #4,WA,Washington
> #5,HI,Hawaii
>
> reader = csv.reader(open('pacific.csv'))


For generality and portability, this should be:
reader = csv.reader(open('pacific.csv', 'rb'))

> for id, abbr, name in reader:
> print '%s is abbreviated: "%s"' % (name, abbr)


and this example doesn't demonstrate why one should use the csv module
instead of:
for line in open('pacific.csv'):
id, abbr, name = line.rstrip().split(',')
# etc
which is quite adequate for the simplistic example file.


 
Reply With Quote
 
John Machin
Guest
Posts: n/a
 
      06-11-2007
On Jun 12, 9:16 am, Steve Howell <(E-Mail Removed)> wrote:

>
> One more suggestion--maybe it could exercise a little
> more of the CVS module, i.e. have something in the
> data that would trip up the ','.split() approach?


The what approach?? Do you mean blah.split(',') ??

Perhaps like an example I posted a few days ago:

"Jack ""The Ripper"" Jones","""Eltsac Ruo"", 123 Smith St",,Paris TX
12345
(name and 3 address fields)
[for avoidance of doubt caused by line wrapping, repr(last_field) is
'Paris TX 12345', and the 2nd-last is '']

 
Reply With Quote
 
mensanator@aol.com
Guest
Posts: n/a
 
      06-12-2007
On Jun 11, 4:56?pm, Steve Howell <(E-Mail Removed)> wrote:
> Hi, I'm offering a challenge to extend the following
> page by one good example:
>
> http://wiki.python.org/moin/SimplePrograms
>
> Right now the page starts off with 15 examples that
> cover lots of ground in Python, but they're still
> scratching the surface. (There are also two Eight
> Queens implementations, but I'm looking to fill the
> gap in lines-of-code, and they're a little long now.)
>
> I'm looking for a good 16-line code example with the
> following qualities:
>
> 1) It introduces some important Python concept that
> the first 15 programs don't cover.
>
> 2) It's not too esoteric. Python newbies are the
> audience (but you can assume they're not new to
> programming in general).
>
> 3) It runs on Python 2.4.
>
> 4) It doesn't just demonstrate a concept; it solves
> a problem at face value. (It can solve a whimsical
> problem, like counting rabbits, but the program itself
> should be "complete" and "suitably simple" for the
> problem at hand.)
>
> 5) You're willing to have your code reviewed by the
> masses.
>
> 6) No major departures from PEP 8.
>
> Any takers?
>
> -- Steve
>
> __________________________________________________ _________________________ _________
> Looking for a deal? Find great prices on flights and hotels with Yahoo! FareChase.http://farechase.yahoo.com/


I just posted a 30-line generator function
on your site. Should I have posted it here
first? Also, why do you count comments and
blank lines instead of lines of executable
code? Are you trying to encourage obfuscation?

 
Reply With Quote
 
Rob Wolfe
Guest
Posts: n/a
 
      06-12-2007

Steve Howell wrote:
> Hi, I'm offering a challenge to extend the following
> page by one good example:
>
> http://wiki.python.org/moin/SimplePrograms


What about simple HTML parsing? As a matter of fact this is not
language concept, but shows the power of Python standard library.
Besides, that's very popular problem among newbies. This program
for example shows all the linked URLs in the HTML document:

<code>
from HTMLParser import HTMLParser

page = '''
<html><head><title>URLs</title></head>
<body>
<ul>
<li><a href="http://domain1/page1">some page1</a></li>
<li><a href="http://domain2/page2">some page2</a></li>
</ul>
</body></html>
'''

class URLLister(HTMLParser):
def reset(self):
HTMLParser.reset(self)
self.urls = []

def handle_starttag(self, tag, attrs):
try:
# get handler for tag and call it e.g. self.start_a
getattr(self, "start_%s" % tag)(attrs)
except AttributeError:
pass

def start_a(self, attrs):
href = [v for k, v in attrs if k == "href"]
if href:
self.urls.extend(href)

parser = URLLister()
parser.feed(page)
parser.close()
for url in parser.urls: print url
</code>

--
Regards,
Rob

 
Reply With Quote
 
Steven Bethard
Guest
Posts: n/a
 
      06-12-2007
Rob Wolfe wrote:
> Steve Howell wrote:
>> Hi, I'm offering a challenge to extend the following
>> page by one good example:
>>
>> http://wiki.python.org/moin/SimplePrograms

>
> What about simple HTML parsing? As a matter of fact this is not
> language concept, but shows the power of Python standard library.
> Besides, that's very popular problem among newbies. This program
> for example shows all the linked URLs in the HTML document:
>
> <code>
> from HTMLParser import HTMLParser


[Sorry if this comes twice, it didn't seem to be showing up]

I'd hate to steer a potential new Python developer to a clumsier library
when Python 2.5 includes ElementTree::

import xml.etree.ElementTree as etree

page = '''
<html><head><title>URLs</title></head>
<body>
<ul>
<li><a href="http://domain1/page1">some page1</a></li>
<li><a href="http://domain2/page2">some page2</a></li>
</ul>
</body></html>
'''

tree = etree.fromstring(page)
for a_node in tree.getiterator('a'):
url = a_node.get('href')
if url is not None:
print url

I know that the wiki page is supposed to be Python 2.4 only, but I'd
rather have no example than an outdated one.

STeVe
 
Reply With Quote
 
Rob Wolfe
Guest
Posts: n/a
 
      06-12-2007
Steven Bethard <(E-Mail Removed)> writes:

> I'd hate to steer a potential new Python developer to a clumsier


"clumsier"???
Try to parse this with your program:

page2 = '''
<html><head><title>URLs</title></head>
<body>
<ul>
<li><a href="http://domain1/page1">some page1</a></li>
<li><a href="http://domain2/page2">some page2</a></li>
</body></html>
'''

> library when Python 2.5 includes ElementTree::
>
> import xml.etree.ElementTree as etree
>
> page = '''
> <html><head><title>URLs</title></head>
> <body>
> <ul>
> <li><a href="http://domain1/page1">some page1</a></li>
> <li><a href="http://domain2/page2">some page2</a></li>
> </ul>
> </body></html>
> '''
>
> tree = etree.fromstring(page)
> for a_node in tree.getiterator('a'):
> url = a_node.get('href')
> if url is not None:
> print url


It might be even one-liner:
print "\n".join((url.get('href', '') for url in tree.findall(".//a")))

But as far as HTML (not XML) is concerned this is not very realistic solution.

>
> I know that the wiki page is supposed to be Python 2.4 only, but I'd
> rather have no example than an outdated one.


This example is by no means "outdated".

--
Regards,
Rob
 
Reply With Quote
 
Steven Bethard
Guest
Posts: n/a
 
      06-12-2007
Rob Wolfe wrote:
> Steven Bethard <(E-Mail Removed)> writes:
>> I'd hate to steer a potential new Python developer to a clumsier

>
> "clumsier"???
> Try to parse this with your program:
>
> page2 = '''
> <html><head><title>URLs</title></head>
> <body>
> <ul>
> <li><a href="http://domain1/page1">some page1</a></li>
> <li><a href="http://domain2/page2">some page2</a></li>
> </body></html>
> '''


If you want to parse invalid HTML, I strongly encourage you to look into
BeautifulSoup. Here's the updated code:

import ElementSoup # http://effbot.org/zone/element-soup.htm
import cStringIO

tree = ElementSoup.parse(cStringIO.StringIO(page2))
for a_node in tree.getiterator('a'):
url = a_node.get('href')
if url is not None:
print url

>> I know that the wiki page is supposed to be Python 2.4 only, but I'd
>> rather have no example than an outdated one.

>
> This example is by no means "outdated".


Given the simplicity of the ElementSoup code above, I'd still contend
that using HTMLParser here shows too complex an answer to too simple a
problem.

STeVe
 
Reply With Quote
 
 
 
Reply

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
Re: SimplePrograms challenge Steve Howell Python 5 06-15-2007 02:00 AM
Re:Routing Challenge Mitch Johnson Cisco 5 10-10-2004 09:42 PM
Routing Challenge Mitch Johnson Cisco 2 10-09-2004 10:39 AM
Parsing challenge... Artco News Perl 6 10-08-2003 02:59 PM
Parsing challenge... Artco News Perl 2 10-07-2003 08:03 PM



Advertisments