2020. 4. 27. 21:30ㆍPython/CodeSignal Algorithm
55. Given a rectangular matrix containing only digits, calculate the number of different 2 × 2 squares in it.
[Example]
For the output should be Here are all 6 different 2 × 2 squares:
|
[Solution]
# <My Code>
def differentSquares(matrix):
l = []
total = 0
for i in range(len(matrix) - 1):
for j in range(len(matrix[0]) - 1):
arr = [[matrix[i][j], matrix[i][j+1]], [matrix[i+1][j], matrix[i+1][j+1]]]
if arr in l:
continue
else:
l.append(arr)
total += 1
return total
# <Best Code>
def differentSquares(matrix):
s = set()
for i in range(len(matrix) - 1):
for j in range(len(matrix[i]) - 1):
s.add((matrix[i][j], matrix[i][j+1], matrix[i+1][j], matrix[i+1][j+1]))
return len(s)
56. Given an integer product, find the smallest positive (i.e. greater than 0) integer the product of whose digits is equal to product. If there is no such integer, return -1 instead.
[Example]
|
[Solution]
# <My Code>
def digitsProduct(product):
divisor = []
minimal = 0
if product == 0: return 10
if product == 1: return 1
for i in range(1, product + 1):
if product % i == 0:
divide = int(product / i)
divisor.append([i, divide])
print(divisor)
if len(divisor) == 2: return -1
for i in range(len(divisor)):
n = int((str(divisor[i][0]) + str(divisor[i][1])))
if i == 0 or minimal > n:
minimal = n
return minimal
# <Best Code>
57. You are given an array of desired filenames in the order of their creation. Since two files cannot have equal names, the one which comes later will have an addition to its name in a form of (k), where k is the smallest positive integer such that the obtained name is not used yet.
Return an array of names that will be given to the files.
[Example]
For names = ["doc", "doc", "image", "doc(1)", "doc"], the output should be fileNaming(names) = ["doc", "doc(1)", "image", "doc(1)(1)", "doc(2)"]. |
[Solution]
# <My Code>
def fileNaming(names):
l = []
for i in range(len(names)):
cnt = 1
if names[i] in l:
while True:
s = names[i] + "(" + str(cnt) + ")"
if s in l:
cnt += 1
else:
l.append(s)
break
else:
l.append(names[i])
return l
# <Best Code>
def fileNaming(names):
for i in range(len(names)):
if names[i] in names[:i]:
j=1
while names[i]+"("+str(j)+")" in names[:i]:
j+=1
names[i]+="("+str(j)+")"
return names
'Python > CodeSignal Algorithm' 카테고리의 다른 글
[Python] CodeSignal 문제 풀이 (58~60) (0) | 2020.04.27 |
---|---|
[Python] CodeSignal 문제 풀이 (52~54) (0) | 2020.04.14 |
[Python] CodeSignal 문제 풀이 (49~51) (0) | 2020.04.14 |
[Python] CodeSignal 문제 풀이 (46~48) (0) | 2020.03.31 |
[Python] CodeSignal 문제 풀이 (43~45) (0) | 2020.03.31 |