[Python] CodeSignal 문제 풀이 (10~12)

2020. 2. 29. 18:30Python/CodeSignal Algorithm

10. Given two strings, find the number of common characters between them.

 

[Example]

For s1 = "aabcc" and s2 = "adcaa", the output should be
commonCharacterCount(s1, s2) = 3.

Strings have 3 common characters - 2 "a"s and 1 "c".

 

[Solution]

def commonCharacterCount(s1, s2):
    s1_digit = list(set(s1))
    s2_digit = list(set(s2))
    sum = 0
    ch = ""
    for i in range(len(s1_digit)):
        if (s1_digit[i] in s2_digit):	#s1_digit의 값이 s2_digit에 존재한다면
            ch = s1_digit[i]
            #더 작은 값을 반환
            result = (s1.count(ch)) if (s1.count(ch) <= s2.count(ch)) else (s2.count(ch))
            sum += result
    print(sum)
    return sum

 

11. Ticket numbers usually consist of an even number of digits. A ticket number is considered lucky if the sum of the first half of the digits is equal to the sum of the second half.

 

[Example]

  • For n = 1230, the output should be
    isLucky(n) = true;
  • For n = 239017, the output should be
    isLucky(n) = false.

 

[Solution]

def isLucky(n):
    strN = str(n)
    digit_len = len(strN)
    half_len = (int)(len(strN) / 2)
    first_half = 0
    second_half = 0
    for i in range(0, half_len):
        first_half += int(strN[i])
    for i in range(half_len, len(strN)):
        second_half += int(strN[i])
    return first_half == second_half

 

12. Some people are standing in a row in a park. There are trees between them which cannot be moved. Your task is to rearrange the people by their heights in a non-descending order without moving the trees. People can be very tall!

 

[Example]

For a = [-1, 150, 190, 170, -1, -1, 160, 180], the output should be
sortByHeight(a) = [-1, 150, 160, 170, -1, -1, 180, 190].

 

[Solution]

def sortByHeight(a):
    list_height = []
    list_location = []
    if (-1 in a):
        for i in range(len(a)):
            if (a[i] != -1):
                list_height.append(a[i])
                list_location.append(i)
        list_height.sort()
        for i in range(len(list_location)):
             a[list_location[i]] = list_height[i]
        return a
    else:
        return sorted(a)