Given an array of integers (x), and a target (t), you must find out if any two consecutive numbers in the array sum to t. If so, remove the second number.

Example:

x = [1, 2, 3, 4, 5]
t = 3 

1+2 = t, so remove 2. No other pairs = t, so rest of array remains:

[1, 3, 4, 5]

Work through the array from left to right.

Return the resulting array.

Source: codewars | Difficulty: EASY
Tags: Fundamentals

Data structures

Starter code: def trouble(x, t):
	

Solutions:
def trouble(x, t):
	arr = [x[0]]
	for c in x[1:]:
		if c + arr[-1] != t:
			arr.append(c)
	return arr


def trouble(array, target):
	i = 0
	while i < len(array) - 1:
		if array[i] + array[i + 1] == target:
			del array[i + 1]
		else:
			i += 1
	return array


def trouble(x, t):
	n = x[:1]
	for i in x[1:]:
		if i + n[-1] != t:
			n.append(i)
	return n


def trouble(x, t):
	res = [x[0]]
	for elem in x[1:]:
		if elem + res[-1] != t:
			res.append(elem)
	return res


def trouble(arr, t):
	i = 0
	while i < len(arr) - 1:
		if arr[i] + arr[i + 1] == t:
			del arr[i + 1]
		else:
			i += 1
	return arr


def trouble(nums, target):
	if len(nums) < 2:
		return nums
	result = []
	left = 0
	right = 1
	while True:
		try:
			if nums[left] + nums[right] != target:
				result.append(nums[left])
				left = right
		except LookupError:
			result.append(nums[left])
			break
		right += 1
	return result


from functools import reduce

def trouble(x, t):
	return reduce(lambda a, u: a + ([u] if not a or a[-1] + u != t else []), x[1:], x[0:1])


def trouble(x, t):
	res = []
	for i in x:
		if not res or res[-1] + i != t:
			res.append(i)
	return res


def trouble(arr, t):
	for i in range(len(arr) - 1):
		if arr[i] + arr[i + 1] == t:
			return trouble(arr[:i + 1] + arr[i + 2:], t)
	return arr


def trouble(x, t):
	while 1:
		for i in range(len(x) - 1):
			if x[i] + x[i + 1] == t:
				x.pop(i + 1)
				break
		else:
			break
	return x