[Tutor] Strings
William Becerra
wbecerra1 at gmail.com
Thu Nov 6 09:51:21 CET 2014
Thank you guys
On Thu, Nov 6, 2014 at 3:39 AM, Dave Angel <davea at davea.name> wrote:
> William Becerra <wbecerra1 at gmail.com> Wrote in message:
> >
>
> have the following code:
> names = "John, Cindy, Peter"
> def find(str, ch, s):
> index = 0
> while index < len(str):
> if s==1:
> for char in names[:4]:
> if str[index] == ch:
> return index + 1
> index = index + 1
> if s==2:
> for char in names[6:11]:
> if str[index] == ch:
> return index + 1
> index = index + 1
> if s==3:
> for char in names[13:]:
> if str[index] == ch:
> return index + 1
> index = index + 1
> return -1
> print find(names,"n", 2)
>
>
>
> and my problem is:
> I intend for the parameter s to tell the interpreter which name to
> look at
> so that i get the index return value related to that name.
> for example:
> John and Cindy both have a letter 'n' but when I call the function
> with an s value of 2 I want it to return the index value of the
> letter n in Cindy and not in John.
>
> Your most immediate problem is that you're using index to fetch
> characters from the original string, and that's only reasonable
> for John. You could make a slice of the original, and search that
> slice. Or you could change the comparison to:
> if char == ch:
>
> The loop could also be cleaner with enumerate.
>
> Your second big problem is that you've hard coded the sizes of the
> first two names in the slice expressions. The magic [6:11] for
> example certainly doesn't belong inside the function.
>
>
> Third is your while loop makes no sense. Each of the if clauses
> won't finish till you're done with the selected substring, so
> you might as well return right away. Drop that line entirely.
>
>
> Anyway, I say you're trying to do too much in the one function. If
> possible change the data structure of names to eliminate one of
> the two tasks, or write two functions, a few lines
> each.
>
> I'd make
> names = ["John", "Cindy", "Peter"]
> And start the function with
> name = names [s-1]
>
> And now the task of the remainder of the function is to search a
> name for a particular character.
>
> --
> DaveA
>
> _______________________________________________
> Tutor maillist - Tutor at python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20141106/857e6ebf/attachment.html>
More information about the Tutor
mailing list