2019-03-29 13:11:00+00:00

At March 16, I just finished the Codemotion-GitHub coding challenge to win a free ticket to Codemotion event in April.

I cannot publish my solution until the challenge is closed on March 28.

As today is March 29, so here is my solution.

#!/bin/python3

import math
import os
import random
import re
import sys


def get_beater(hand):
    if hand == 'P':
        return 'S'

    if hand == 'S':
        return 'R'

    if hand == 'R':
        return 'P'


def compare_hand(poi_hand, other_hand):
    """
    returns True if poi win
    """
    return get_beater(other_hand) == poi_hand


def conditional_inc_num_changes(a, formations, num_changes):
    len_formations = len(formations)
    if len_formations < 2:
        return num_changes

    a_hand = formations[a]
    new_a = a
    new_formations = []
    new_num_changes = num_changes
    for i in range(0, len_formations, 2):
        if i + 1 == len_formations:  # get free pass
            new_formations.append(formations[i])
            if i == a:
                new_a = len(new_formations) - 1
        else:
            if a == i or a == (i + 1):
                if a == i:
                    beater_hand = get_beater(formations[i + 1])
                else:
                    beater_hand = get_beater(formations[i])
                if a_hand is not None and a_hand != beater_hand:
                    new_num_changes += 1

                new_formations.append(beater_hand)
                new_a = len(new_formations) - 1
            else:
                if formations[i] != formations[i + 1]:
                    if compare_hand(formations[i], formations[i + 1]):
                        new_formations.append(formations[i])
                    else:
                        new_formations.append(formations[i + 1])

    return conditional_inc_num_changes(new_a, new_formations, new_num_changes)


# Complete the 'handFormationChange' function below.
#
# The function is expected to return an INTEGER.
# The function accepts following parameters:
#  1. INTEGER n
#  2. INTEGER a
#  3. STRING formations
#

def handFormationChange(n, a, formations):
    """
    2 <= n <= 10**5
    0 <= a <= n
    """
    formations = list(formations)
    formations[a:0] = [None]
    return conditional_inc_num_changes(a, formations, 0)


# The provided boilerplate code
if __name__ == '__main__':
    fptr = open(os.environ['OUTPUT_PATH'], 'w')

    n = int(input().strip())

    a = int(input().strip())

    formations = input()

    result = handFormationChange(n, a, formations)

    fptr.write(str(result) + '\n')

    fptr.close()

Sample Input 2

4
1
PRS

Sample Output 2

1

Sample Input 3

6
2
PPSRP

Sample Output 3

1