Sign in to follow this  

(python) Help utilizing my find function...

This topic is 4105 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Here's the deal, here is my origonal find function code:
def find(strng, ch, startat):
    index = startat
    while index < len(strng):
        if strng[index] == ch:
            return index
        index = index + 1
    return -1
This will find the position of a letter in a string. I have to make a new function called countletters that will use the find function (which I don't think I'm allowed to change) to count the number of times a letter appears in a string. Here's where I decided to stop:
def countletters(s, l):
    count = 0
    x = 0
    for char in s:
        if find(s, l, x) != -1:
            count = count + 1
    print count
            
        

            
def find(strng, ch, startat):
    index = startat
    while index < len(strng):
        if strng[index] == ch:
            return index
        index = index + 1
    return -1

countletters("vanilla", "a")
Before I think and confuse myself any further, I wanted to see if someone here could steer me in the right direction. Thanks in advance.

Share this post


Link to post
Share on other sites
Quote:
Original post by Doggan
Is this for practice/homework?

If yes, Oluseyi has the answer.

If no:

import string
print str.count("vanilla", "a")


It's a book assignment, not homework, and I'm still trying out Oluseyi's code, but I haven't got it to work yet.

Share this post


Link to post
Share on other sites
Quote:
Original post by Doggan
def countletters(s, l):
count = 0
x = 0
while True:
x = find(s, l, x)
if x == -1:
break
x += 1
count += 1

print count


Slight modifcation to original code, and surround in a loop.


Thank you. I see the logic now, x = the position of the letter, thus the letter will be incrememnted by one, and the first letter won't be counted for again. After that, a second letter of the same kind (if one is present), will increment count by one. Wish I could have thought of that.

Share this post


Link to post
Share on other sites

This topic is 4105 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this