2020. 3. 31. 21:27ㆍPython/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]
|
[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]
|
[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]))
'Python > CodeSignal Algorithm' 카테고리의 다른 글
[Python] CodeSignal 문제 풀이 (46~48) (0) | 2020.03.31 |
---|---|
[Python] CodeSignal 문제 풀이 (43~45) (0) | 2020.03.31 |
[Python] CodeSignal 문제 풀이 (37~39) (0) | 2020.03.31 |
[Python] CodeSignal 문제 풀이 (34~36) (0) | 2020.03.31 |
[Python] CodeSignal 문제 풀이 (33~35) (0) | 2020.03.21 |