Write a function `insertDash(num)`/`InsertDash(int num)` that will insert dashes ('-') between each two odd numbers in num. For example: if num is 454793 the output should be 4547-9-3. Don't count zero as an odd number.

Note that the number will always be non-negative (>= 0).

Source: codewars | Difficulty: EASY
Tags: String algorithms

Fundamentals

Data structures

Starter code: def insert_dash(num):
	

Solutions:
import re

def insert_dash(num):
	return re.sub('([13579])(?=[13579])', '\\1-', str(num))


import re

def insert_dash(num):
	return re.sub('[13579](?=[13579])', '\\g<0>-', str(num))


def insert_dash(num):
	odd = False
	result = []
	for n in str(num):
		num = n
		if int(n) % 2 == 0:
			odd = False
		elif odd:
			num = '-' + num
		else:
			odd = True
		result.append(num)
	return ''.join(result)


def insert_dash(num):

	def odd(c):
		return not ord(c) & 1 ^ 1
	a = []
	for digit in str(num):
		if odd(digit) and a and odd(a[-1]):
			a.append('-')
		a.append(digit)
	return ''.join(a)


def is_odd(num):
	return not int(num) % 2 == 0

def insert_dash(num):
	num_str = str(num)
	new_str = num_str[0]
	for i in range(1, len(num_str)):
		if is_odd(num_str[i]) and is_odd(num_str[i - 1]):
			new_str += '-' + num_str[i]
		else:
			new_str += num_str[i]
	return new_str


def insert_dash(num):
	digits = [d for d in str(num)]
	for i in range(len(digits) - 1):
		if int(digits[i]) % 2 and int(digits[i + 1]) % 2:
			digits[i] = digits[i] + '-'
	return ''.join(digits)


from itertools import groupby
is_odd = set('13579').__contains__

def insert_dash(num: int) -> str:
	return ''.join((('-' if k else '').join(g) for (k, g) in groupby(str(num), key=is_odd)))


def insert_dash(num):
	num = str(num)
	ans = ''
	for i in range(len(num) - 1):
		ans += num[i]
		if int(num[i]) % 2 == 1 and int(num[i + 1]) % 2 == 1:
			ans += '-'
	ans += num[-1]
	return ans