In order to prove it's success and gain funding, the wilderness zoo needs to prove to environmentalists that it has x number of mating pairs of bears. 

You must check within string (s) to find all of the mating pairs, and return a string containing only them. Line them up for inspection.

Rules:
Bears are either 'B' (male) or '8' (female),
Bears must be together in male/female pairs 'B8' or '8B',
Mating pairs must involve two distinct bears each ('B8B' may look fun, but does not count as two pairs).

Return an array containing a string of only the mating pairs available. e.g:

'EvHB8KN8ik8BiyxfeyKBmiCMj' ---> 'B88B'    (empty string if there are no pairs)

and true if the number is more than or equal to x, false if not:

(6, 'EvHB8KN8ik8BiyxfeyKBmiCMj') ---> ['B88B', false];

x will always be a positive integer, and s will never be empty

Source: codewars | Difficulty: EASY
Tags: String algorithms

Fundamentals

Data structures

Starter code: def bears(x,s):
	

Solutions:
import re

def bears(n, s):
	a = re.findall('B8|8B', s)
	return [''.join(a), len(a) >= n]


import re

def bears(x, s):
	r = re.findall('8B|B8', s)
	return [''.join(r), len(r) >= x]


from regex import findall

def bears(x, s):
	res = findall('(B8|8B)', s)
	return [''.join(res), len(res) >= x]


import re

def bears(n, stg):
	pairs = re.findall('B8|8B', stg)
	return [''.join(pairs), len(pairs) >= n]


def bears(x, s):
	k = []
	i = 0
	while i < len(s) - 1:
		if s[i] == 'B' and s[i + 1] == '8' or (s[i] == '8' and s[i + 1] == 'B'):
			k.append(s[i] + s[i + 1])
			i += 2
		else:
			i += 1
	return [''.join(k), len(k) >= x] if k else ['', len(k) >= x]


def bears(x, s):
	couples = ['B8', '8B']
	matches = ['', False]
	counter = 0
	ln = len(s)
	i = 0
	while i < ln:
		pair = s[i:i + 2]
		if pair in couples:
			matches[0] += pair
			counter += 1
			i += 2
		else:
			i += 1
	if counter >= x:
		matches[1] = True
	return matches


def bears(x, s):
	result = []
	bears = []
	while len(s) > 1:
		if s[0] == 'B' and s[1] == '8':
			s = s[2:]
			bears.append('B8')
		elif s[0] == '8' and s[1] == 'B':
			s = s[2:]
			bears.append('8B')
		else:
			s = s[1:]
	result.append(''.join(bears))
	test = len(bears) * 2 >= x
	result.append(test)
	return result


bears = lambda x, s, k='', i=0: [k, len(k) >= x * 2] if i == len(s) else bears(x, s, k + s[i:i + 2], i + 2) if s[i:i + 2] in ['8B', 'B8'] else bears(x, s, k, i + 1)


bears = lambda n, s: (lambda a: [''.join(a), n <= len(a)])(__import__('re').findall('B8|8B', s))