Syntax error Count all prefixes in given string with greatest frequency using Python

Count all prefixes in given string with greatest frequency using Python



In this tutorial, we are going to write a program that counts and prints the words with a higher frequency of an alphabet than the second one.

Take a string and two alphabets. The prefixes with a higher frequency of the first alphabet will be printed. And display the count at the end of the output.

Let's see some examples.

Input

string:- apple
alphabets:- p, e

Output

ap
app
appl
apple 4

Input

string:- apple
alphabets:- e, p

Output

0

Let's see the steps to write the code.

  • Define a function and write the code in it.

  • Initialize count to 0 and an empty string.

  • Iterate over the string.

  • Get the prefix using the string slicing and index. And store it in an empty string.

  • Compare the alphabet frequency in the prefix.

  • Print and increment the count if satisfied.

  • Print the count at the end.

Example

# defining a function for multiple calles
def prefixes(string, _1, _2):
   # count count = 0
   # empty string for comparison
   prefix = ""
   # iterating over the string
   for i in range(len(string)):
      # getting the prefix from the string
      prefix = string[:i + 1]
      # comparing the count of alphabets in the prefix
      if prefix.count(_1) > prefix.count(_2):
      # printing the prefix if success
      print(prefix)
      # incrementing the count by 1
      count += 1
   # printing the count
   print(f"Total prefixes matched: {count}")
if __name__ == '__main__':
   # invokging the function
   print(f"----------------apple p e---------------------")
   prefixes('apple', 'p', 'e')
   print()
   print(f"----------------apple e p---------------------")
   prefixes('apple', 'e', 'p')

Output

If you run the above code, you will get the following result.

----------------apple p e---------------------
ap
app
appl
apple
Total prefixes matched: 4
----------------apple e p---------------------
Total prefixes matched: 0

Conclusion

If you are facing any problems in understanding the code, mention them in the comment section.

Updated on: 2020-02-12T11:10:44+05:30

627 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements