def _count_substr(stack, needle):
    """
    Counts occurrences of needle in stack.
    Example: in aaaa there are 3 occurrences of aa
    """
    count = 0
    for i in range(len(stack) - len(needle) + 1):
        if stack[i: i + len(needle)] == needle:
            count += 1
    return count