[Python] CodeSignal 문제 풀이 (16~18)

2020. 3. 12. 20:50Python/CodeSignal Algorithm

16. Two arrays are called similar if one can be obtained from another by swapping at most one pair of elements in one of the arrays.

Given two arrays a and b, check whether they are similar.

 

[Example]

  • For a = [1, 2, 3] and b = [1, 2, 3], the output should be
    areSimilar(a, b) = true.

    The arrays are equal, no need to swap any elements.

  • For a = [1, 2, 3] and b = [2, 1, 3], the output should be
    areSimilar(a, b) = true.

    We can obtain b from a by swapping 2 and 1 in b.

  • For a = [1, 2, 2] and b = [2, 1, 1], the output should be
    areSimilar(a, b) = false.

    Any swap of any two elements either in a or in b won't make a and b equal.

 

[Solution]

<My Code>
def areSimilar(a, b):
    cnt = 0
    if(sorted(a) == sorted(b)):
        for i in range(len(a)):
            if(a[i] != b[i]):
                cnt += 1
        return cnt < 3
    else:
        return False

<Best Code>
def areSimilar(a, b):
    return sorted(a) == sorted(b) and sum(i != j for i, j in zip(a, b)) < 3

 

17. You are given an array of integers. On each move you are allowed to increase exactly one of its element by one. Find the minimal number of moves required to obtain a strictly increasing sequence from the input.

 

[Example]

For inputArray = [1, 1, 1], the output should be
arrayChange(inputArray) = 3.

 

[Solution]

<My Code>
def arrayChange(inputArray):
    a = inputArray
    total = 0
    
    for i in range(len(a) - 1):
        if(a[i+1] <= a[i]):
            total +=  a[i] - a[i+1] + 1
            a[i+1] += a[i] - a[i+1] + 1
    return total
    
<Best Code>
def arrayChange(inputArray):
    a = 0
    for i in range(1, len(inputArray)):
        if inputArray[i] <= inputArray[i - 1]:
            f = (inputArray[i - 1] - inputArray[i]) + 1
            inputArray[i] = inputArray[i - 1] + 1
            a += f
    return a

 

18. Given a string, find out if its characters can be rearranged to form a palindrome.

 

[Example]

For inputString = "aabb", the output should be
palindromeRearranging(inputString) = true.

We can rearrange "aabb" to make "abba", which is a palindrome.

 

[Solution]

<My Code>
def palindromeRearranging(inputString):
    s = inputString
    ss = list(set(inputString))
    sl = len(s) % 2
    evenCnt = 0
    for i in range(len(ss)):
        cnt = 0
        for j in range(len(s)):
            if(ss[i] == s[j]):
                cnt += 1
        if(cnt % 2 == 1):
            evenCnt += 1
    return True if (evenCnt < 2) else False
    
<Best Code>
def palindromeRearranging(inputString):
    return sum([inputString.count(i)%2 for i in set(inputString)]) <= 1