Solution 1

def count_in_position(a_string, a_char, position_type):
    count = 0
    for index, current_char in enumerate(a_string):
        if a_char == current_char:
            if position_type == 'even' and index % 2 == 0:
                count += 1
            elif position_type == 'odd' and index % 2 != 0:
                count += 1

    return count

Count in even-odd positions

We're going to extend our counting from strings by adding a subtle twist. You'll need to write a count_in_position function that receives three parameters: a word/sentence, a character to find, and a modifier like even or odd. Example:

# Example 1
#         0123456789
phrase = 'aXbcXdXXeX'
count_in_position(phrase, 'X', 'even')  # 2

Example 1 returns only 2 because there are only 2 characters X with an even index/position (positions 4 and 6). Let's see another example; using the same phrase, if we ask for 'odd' positions we'd get:

# Example 2
#         0123456789
phrase = 'aXbcXdXXeX'
count_in_position(phrase, 'X', 'odd')  # 3

We get 3, because we have three 'X' with an odd index/position (positions 1, 7 and 9).

Test Cases

test no chars in odd positions - Run Test

def test_no_chars_in_odd_positions():
    #         0123456789
    phrase = 'abXcXdefXg'
    assert count_in_position(phrase, 'X', 'odd') == 0

test a few chars in even positions - Run Test

def test_a_few_chars_in_even_positions():
    #         0123456789
    phrase = 'aXbcXdXXeX'
    assert count_in_position(phrase, 'X', 'even') == 2

test only one char in even positions - Run Test

def test_only_one_char_in_even_positions():
    #         0123456789
    phrase = 'abXXcdeXfX'
    assert count_in_position(phrase, 'X', 'even') == 1

test no chars in even positions - Run Test

def test_no_chars_in_even_positions():
    #         0123456789
    phrase = 'aXbXcdeXfX'
    assert count_in_position(phrase, 'X', 'even') == 0

test only one char in odd positions - Run Test

def test_only_one_char_in_odd_positions():
    #         0123456789
    phrase = 'aXXbcdXfXg'
    assert count_in_position(phrase, 'X', 'odd') == 1

test a few chars in odd positions - Run Test

def test_a_few_chars_in_odd_positions():
    #         0123456789
    phrase = 'aXbcXdXXeX'
    assert count_in_position(phrase, 'X', 'odd') == 3


def test_only_one_char_in_odd_positions():
    #         0123456789
    phrase = 'aXXbcdXfXg'
    assert count_in_position(phrase, 'X', 'odd') == 1
def count_in_position(a_string, a_char, position_type): pass