Doctest failing

ting at thsu.org ting at thsu.org
Sun Sep 11 04:12:37 CEST 2011


On Sep 10, 7:47 am, Peter Otten <__pete... at web.de> wrote:
> Tigerstyle wrote:
> > I'm strugglin with some homework stuff and am hoping you can help me
> > out here.
>
> > This is the code:
>
> > small_words = ('into', 'the', 'a', 'of', 'at', 'in', 'for', 'on')
> >     new_title = []
> >     title_split = title.strip().lower().split()
> >     for word in title_split:
> >         if title_split[0] in small_words:
> >             new_title.append(word.title())
> >         elif word in small_words:
> >             new_title.append(word.lower())
> >         else:
> >             new_title.append(word.title())
>
> The logic of the for-loop is flawed; the expression
>
> title_split[0] in small_words
>
> will always evaluate to True if the first word is a "small word", even when
> the loop is already past the first word. You can work around that with a
> flag along these lines
>
> first = True
> for word in title_split:
>     if first:
>         # special treatment for the first word
>         first = False
>     else:
>         # put checks for all words but the first here
>     new_title.append(fixed_word) # assuming you have stored the titlecased
>                                  # or lowercased word in the fixed_word
>                                  # variable

Another way to tackle this is to just capitalize the entire sentence
before returning it.

new_title = []
title_split = title.strip().lower().split()
for word in title_split:
  if word in small_words:
    new_title.append(word.lower())
  else:
    new_title.append(word.title())
return(''.join(new_title).capitalize())

However, I'm only helping with your homework, because I want to point
out that doctest comments should be *readable*. Don't just throw them
in, take the extra 10-15 seconds to make them easier on the eyes. In
the workplace, months will pass before you review this code again, so
you want to make it easier for an older version of yourself to
remember it.

And it takes very little effort to make it readable. Here's your
doctest string, reformatted with just a tiny bit more whitespace. I
even cut out a sentence.

def book_title(title):
  """
  All words EXCEPT for small words are made title case
  unless the string starts with a preposition, in which
  case the word is correctly capitalized.

  >>> book_title('DIVE Into python')
  'Dive into Python'
  >>> book_title('the great gatsby')
  'The Great Gatsby'
  >>> book_title('the WORKS OF AleXANDer dumas')
  'The Works of Alexander Dumas'
  """
--
// T.Hsu



More information about the Python-list mailing list