given a string s consisting of stars and bars

The problem of given a string s consisting of stars and bars

This problem is that you are given a string s consisting of stars and bars. You have to count the number of stars in between the two bars. The code for the same is:

 

Lis=[x for x in range(len(S)) if S[x]=='|']
min_idx=Lis[0]
max_idx=Lis[-1]
count_of_stars=S[min_idx:max_idx].count('&')

 

The above code is right but the problem is that it does not work for the larger input value. It is not an optimal solution. So, our major goal is to make a more optimal solution for this. 

Solution

Python’s Strip() function trims or eliminates the specified characters from the start and end of the original string. The strip() method’s default behavior is to eliminate the whitespace at the beginning and end of the text.

The built-in Python function count() provides the count of times an object appears in a list. One of the built-in functions in Python is the count() method. As suggested by the name, it returns the number of times a given value appears in a string or list.

Python’s count() function syntax

The syntax for Python’s count() function is as follows: count(substring/character, start=, end=) for a string.

If you use the Python String strip() function on any other data type, such as a list, tuple, or other, it will produce an error.

The simple solution for the above problem in python is that: 

 

S='&|&&|&&&|&'

print(S.strip('&').count('&'))

The strip function will divide the string as per the character given in the function. The count function will count the number of characters passed in that function. 

 

Also Read: show-doc not working in ruby pry

 

 

Share this post

Leave a Reply

Your email address will not be published. Required fields are marked *