I am pretty sure this question has been asked about a gazillion times, but I can not find a satisfying answer. I am trying to iterate through a list and find how many occurrences of 'B'
are immediately preceded by 'A'
. I have a solution, but I am sure it is far from perfect. In C++ I'd do something like (with about 10 variations):
int main()
{
vector<char> charList={'A', 'B', 'D', 'B', 'C', 'A', 'B'};
int count=0;
char prevElem = '\0';
for(auto x: charList)
{
if( x == 'B' && prevElem =='A')
++count;
prevElem = x;
}
cout << "Count = " << count << endl;
return 0;
}
What is the right way to do it in Python? I mean the simplest solution is obvious, but what should I do if the data I have is in the form of iterator with the lazy iterable under it and I do not want to go over that iterator twice?