[Python] CodeSignal 문제 풀이 (40~42)

2020. 3. 31. 21:27Python/CodeSignal Algorithm

 

 

 

40. Given a string, output its longest prefix which contains only digits.

[Example]

For inputString = "123aa1", the output should be
longestDigitsPrefix(inputString) = "123".

 

[Solution] -ing

#<My Code>
def longestDigitsPrefix(inputString):
    a = inputString.split()
    result = ""

    if inputString.isdigit(): return inputString
    for i in range(len(a)):
        s = ""
        if  any(sym in a[i] for sym in '!@#$%^&*()'):
            continue
        for j in range(len(a[i])):
            if not a[i].isdigit() and a[i][j].isdigit():
                s += a[i][j]
            else:
                if len(result) < len(s):
                    result = s
    return result


#<Best Code>

 

 

41. Let's define digit degree of some positive integer as the number of times we need to replace this number with the sum of its digits until we get to a one digit number.

Given an integer, find its digit degree.

 

[Example]

  • For n = 5, the output should be
    digitDegree(n) = 0;
  • For n = 100, the output should be
    digitDegree(n) = 1.
    1 + 0 + 0 = 1.
  • For n = 91, the output should be
    digitDegree(n) = 2.
    9 + 1 = 10 -> 1 + 0 = 1.

 

[Solution]

#<My Code>
def digitDegree(n):
    s = str(n)
    l = len(s)
    cnt = 0

    while True:
        if l == 1: return cnt

        n = 0
        for i in range(len(s)):
            n += int(s[i])
        s = str(n)
        l = len(s)
        cnt += 1

#<Best Code>
def digitDegree(n):
    
    if n < 10:
        return 0
    
    sumOfDigits = sum([int(i) for i in str(n)])
    
    return digitDegree(sumOfDigits) + 1

 

 

42. Given the positions of a white bishop and a black pawn on the standard chess board, determine whether the bishop can capture the pawn in one move.

The bishop has no restrictions in distance for each move, but is limited to diagonal movement. Check out the example below to see how it can move:

 

 

[Example]

  • For bishop = "a1" and pawn = "c3", the output should be
    bishopAndPawn(bishop, pawn) = true.

  • For bishop = "h1" and pawn = "h3", the output should be
    bishopAndPawn(bishop, pawn) = false.

  • For bishop = "h1" and pawn = "h3", the output should be
    bishopAndPawn(bishop, pawn) = false.

 

[Solution]

#<My Code>
def bishopAndPawn(bishop, pawn):
    b = bishop
    p = pawn

    if b[0] == p[0] or b[1] == p[1]: return False
    if abs(ord(b[0]) - ord(p[0])) == abs(int(b[1]) - int(p[1])): return True
    else: return False

#<Best Code>
def bishopAndPawn(bishop, pawn):
    return abs(ord(bishop[0])-ord(pawn[0]))==abs(int(pawn[1])-int(bishop[1]))