Find the Number of Stars Between Two Bars in a String - Python

I was given a String S='&|&&|&&&|&' where we should get the number of stars between two bars in the given string. So the output here should be 5. And here's my code:

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 problem I faced was my code was getting timed out for larger inputs in a coding platform. can anyone suggest a better way to reduce the time complexity here?

0

2 Answers

Try to strip and count:

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

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

You could use the following regular expression with lookaheads to match & only between bars:

import re
S = '&|&&|&&&|&' 

len(''.join(re.findall(r'(?<=\|)(\&+)(?=\|)', S)))
# 5

Where:

re.findall(r'(?<=\|)(\&+)(?=\|)', S)
# ['&&', '&&&']

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Elena Rostova

Elena Rostova

Lead Health, Wellness & Medical Journalist

Elena Rostova holds a Master's degree in Public Health Journalism. She covers groundbreaking medical research, holistic wellness trends, mental health awareness, and nutritional science.

Share this article
Twitter Facebook Pinterest