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...
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?
2 Answers
Try to strip and count:
S='&|&&|&&&|&'
print(S.strip('&').count('&'))
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)
# ['&&', '&&&']