From Wikipedia : "The n-back task is a continuous performance task that is commonly used as an assessment in cognitive neuroscience to measure a part of working memory and working memory capacity. [...] The subject is presented with a sequence of stimuli, and the task consists of indicating when the current stimulus matches the one from n steps earlier in the sequence. The load factor n can be adjusted to make the task more or less difficult."

In this kata, your task is to "teach" your computer to do the n-back task. Specifically, you will be implementing a function that counts the number of "targets" (stimuli that match the one from n steps earlier) in a sequence of digits. Your function will take two parameters :

n, a positive integer equal to the number of steps to look back to find a match
sequence, a sequence of digits containing 0 or more targets

A few hints :

The first digit in a sequence can never be a target
Targets can be "chained" together (e.g., for n = 1 and sequence = [1, 1, 1], there are 2 targets)

Source: codewars | Difficulty: EASY
Tags: Fundamentals

Starter code: def count_targets(n, sequence):
	

Solutions:
def count_targets(n, sequence):
	return sum((a == b for (a, b) in zip(sequence, sequence[n:])))


def count_targets(n, s):
	return sum((s[i] == s[i - n] for i in range(n, len(s))))


def count_targets(n, sequence):
	return sum((1 for (a, b) in zip(sequence, sequence[n:]) if a == b))


def count_targets(n, seq):
	return sum((a == b for (a, b) in zip(seq, seq[n:])))


def count_targets(n, sequence):
	return sum((y == x for (x, y) in zip(sequence, sequence[n:])))


from collections import deque

def count_targets(n, sequence):
	q = deque(sequence[:n], maxlen=n)
	return sum(((x == q[0], q.append(x))[0] for x in sequence[n:]))


def count_targets(n, seq):
	count = 0
	for i in range(n, len(seq)):
		if seq[i] == seq[i - n]:
			count += 1
	return count


def count_targets(n, a):
	return sum((a[i] == a[i - n] for i in range(n, len(a))))


def count_targets(n, sequence):
	return sum([1 for i in range(n, len(sequence)) if sequence[i] == sequence[i - n]])


def count_targets(n, a):
	res = 0
	for (i, v) in enumerate(a):
		if i - n < 0:
			continue
		if v == a[i - n]:
			res += 1
	return res