Bob Counter in Python

后端 未结 8 1297
名媛妹妹
名媛妹妹 2021-01-28 11:25

Using Python 2.7, I was attempting to count the number of occurances of \'bob\' in the phrase \'bobbbobobboobobookobobbobbboj.\' To do this, I wrote the code below:



        
相关标签:
8条回答
  • 2021-01-28 11:33

    If you want to do it the Pythonic way, then you'll want to read up on the string find function.

    If you want to learn how make a string find function, then you'll want to read up on string searching algorithms.

    0 讨论(0)
  • 2021-01-28 11:38

    let's see if we can help you out.

    Your code is

    s='bobbbobobboobobookobobbobbboj'
    
     for i in s:
    
         if(i=='BOB' or i=='bob'):
            b=b+1
    

    It is important to think about this- a string like "s" is a list of characters. When you do for i in s, you are looping through each individual character.

    on the first iteration, i == 'b', on the second one it equals 'o' and so on.

    What you want is something that checks sections of code. a way of doing that would be

    for i in range(len(s)):
        if s[i:i+4] == "bob":
    

    The reason this works is that range returns a list of numbers in order, so it will go 0, 1, 2, 3... the [i:i+4] part cuts out a section of the string based on the how far into the string it is. For your string s[0:2] would be "bob" (it starts with 0).

    I left several problems... for example, if you let it run to the end you'll have a problem (if s is 10 characters long and you try to do s[9:12] you will get an error) ... but that should help you get going

    0 讨论(0)
  • 2021-01-28 11:38
    s = ('bobobobobobob')
    count = 0
    
    for i in range(len(s)):
        if s[i:i+3] == "bob":
            count += 1
    
    print ('Number of times bob occurs is: ' + str(count))
    
    0 讨论(0)
  • 2021-01-28 11:46
    >>> s = 'bobbbobobboobobookobobbobbboj'
    >>> term = 'bob'
    sum(1 for i, j in enumerate(s) if s[i:i+len(term)] == term)
    6
    
    0 讨论(0)
  • 2021-01-28 11:50
    def bobcount(x):
        bobcounter = 0
        for i in range(len(x)):
            if (x[i:i+3]=="bob") or (x[i:i+3]=="BOB"):
                bobcounter = bobcounter + 1
        return bobcounter
    

    This is an extension of Paul's answer. The result of the code is:

    bobcount("bobobobBOBBOB")
    5
    
    0 讨论(0)
  • 2021-01-28 11:52

    Guess i am a little bit late, but you can try this:

    from re import findall
    
        def bobcount(word):
            return len(findall(r'(bob)', word.lower()))
    
    0 讨论(0)
提交回复
热议问题