Re: [Tutor] strings

Danny Yoo dyoo at hkn.eecs.berkeley.edu
Tue Dec 9 15:28:55 EST 2003



> i'm having a little trouble with this exercise problem. We're supposed
> to create a function called findchr(string,char)

[some text cut]

> The part where i'm having trouble is returning the index of the first
> occurrence of char. Any help would be appreciated. Thanks

Hi trypticon,


Please don't take this the wrong way, but you do understand that that
"part" that you're having trouble with is the point of the whole exercise,
right?


One way to get a better understanding of a problem is to try a simpler
version of it.  This is one of the problem-solving strategies that G.
Polya talks about in his book "How to Solve It":

    http://www.math.utah.edu/~alfeld/math/polya.html

Can you think of simpler versions of the problem?


The original problem allows us to pass strings of any length, and maybe
you're running into problem trying to account for this.  If so, here's one
way to simplify the problem: what if you're only working with strings of
three characters only?

Say that you're writing a version of the code called findchr3() that takes
a three-character string, and a character to search for.  It'd work
something like this:

###
>>> findchr3("abc", "a")
0
>>> findchr3("abc", "c")
2
>>> findchr3("abc", "z")
-1
###

findchr3() can assume that the first argument is always a string of three
characters.  Would you be able to write findchr3()?  If not, then that's
something you may want to try doing first, before tackling the more
general problem.


Also, you may want to try browsing through one of the tutorials on:

    http://www.python.org/topics/learn/non-prog.html

In particular:

    http://www.freenetpages.co.uk/hp/alan.gauld/

is a good tutorial to try out.  If you understand the concept of "loops",
you should know enough to solve your original problem.


Good luck to you!




More information about the Tutor mailing list