简体   繁体   中英

Python code to count the recurrence of a letter in a word

I need your help to calculate the recurrence of a letter in the word.

Input (string): HelloWorld
Output: H1e1l3o2W1r1d1  

You need a run-length-encoding algorithm on the input.

GeeksforGeeks has a great article on this:

https://www.geeksforgeeks.org/run-length-encoding-python/

# Python code for run length encoding 
from collections import OrderedDict 
def runLengthEncoding(input): 
  
    # Generate ordered dictionary of all lower 
    # case alphabets, its output will be  
    # dict = {'w':0, 'a':0, 'd':0, 'e':0, 'x':0} 
    dict=OrderedDict.fromkeys(input, 0) 
  
    # Now iterate through input string to calculate  
    # frequency of each character, its output will be  
    # dict = {'w':4,'a':3,'d':1,'e':1,'x':6} 
    for ch in input: 
        dict[ch] += 1
  
    # now iterate through dictionary to make  
    # output string from (key,value) pairs 
    output = '' 
    for key,value in dict.items(): 
         output = output + key + str(value) 
    return output 
   
# Driver function 
if __name__ == "__main__": 
    input="wwwwaaadexxxxxx"
    print (runLengthEncoding(input))

Output:

'w4a3d1e1x6'

Your Example:

input = 'hello world'
print(runLengthEncoding(input))

Output:

'h1e1l3o2 1w1r1d1'

Exactly how you wanted it.

Above code from GeeksforGeeks link.

As mentioned by others, you can use str.count(). One easy approach is to look at the first letter, count it, then delete all instances of it from the string and repeat. A simple recursive answer might look like:

def count(word):
    if len(word) == 0:
        return ""
    return word[0]+str(word.count(word[0]))+count(word[1:].replace(word[0], ""))

use string.count() .

The syntax is as follows:

string.count(substring, [start_index],[end_index])

substring is the letter you are trying to find, [start_index] is the letter at which to start searching (remember, python starts at 0 when using indexes) and [end_index] is at which letter to stop searching.

I think this function should do the trick:

def countoccurences(word, character):
    occuresin =[]
    for letter in word:
        if letter == character:
            occuresin.append(letter)
        
    print("Letter", character, " occurs in string: ", str(len(occuresin)), " times.")
    return len(occuresin)

countoccurences("1se3sr4g45h7e5q3e", 'e')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM