2020. 3. 12. 20:50ㆍPython/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]
|
[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 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
'Python > CodeSignal Algorithm' 카테고리의 다른 글
[Python] CodeSignal 문제 풀이 (22~24) (0) | 2020.03.12 |
---|---|
[Python] CodeSignal 문제 풀이 (19~21) (0) | 2020.03.12 |
[Python] CodeSignal 문제 풀이 (13~15) (0) | 2020.03.12 |
[Python] CodeSignal 문제 풀이 (10~12) (0) | 2020.02.29 |
[Python] CodeSignal 문제 풀이 (7~9) (0) | 2020.02.16 |