Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #41678 > unrolled thread

Re: problem with function

Started byTerry Reedy <tjreedy@udel.edu>
First post2013-03-21 19:20 -0400
Last post2013-03-21 19:20 -0400
Articles 1 — 1 participant

Back to article view | Back to comp.lang.python

This discussion starts older than the indexed window; earlier articles aren't shown. The article labeled Started by below is the oldest one visible, not the original post.


Contents

  Re: problem with function Terry Reedy <tjreedy@udel.edu> - 2013-03-21 19:20 -0400

#41678 — Re: problem with function

FromTerry Reedy <tjreedy@udel.edu>
Date2013-03-21 19:20 -0400
SubjectRe: problem with function
Message-ID<mailman.3607.1363908076.2939.python-list@python.org>
On 3/21/2013 2:31 PM, leonardo selmi wrote:

> i wrote the following code:
>
> def find(word, letter):
>      index = 0
>      while index < len(word):
>          if word[index] == letter:
>              return index
>          index = index + 1
>      return -1

Since this is a learning exercise, consider the following.

def find(word, letter):
     for index, let in enumerate(word):
         if let  == letter:
             return index
     return -1

for w, l, n in (('abc', 'a', 0), ('abc', 'c', 2), ('abc', 'd', -1)):
     assert find(w, l)  == n
print("no news is good news")

I copied the code, wrote the test, ran it, and it passed. I then 
re-wrote until syntax errors were gone and the new version passed. For 
loops are specialized, easier-to-write version of while loops that scan 
the items of a collection (iterable). Learn them and use them well. 
Learn to write automated tests as soon as possible.

-- 
Terry Jan Reedy

[toc] | [standalone]


Back to top | Article view | comp.lang.python


csiph-web