[Python] CodeSignal 문제 풀이 (25~27)
2020. 3. 12. 21:05ㆍPython/CodeSignal Algorithm
25. Given an array of integers, replace all the occurrences of elemToReplace with substitutionElem.
[Example]
For inputArray = [1, 2, 1], elemToReplace = 1, and substitutionElem = 3, the output should be arrayReplace(inputArray, elemToReplace, substitutionElem) = [3, 2, 3]. |
[Solution]
#<My Code>
def arrayReplace(inputArray, elemToReplace, substitutionElem):
a = inputArray
for i in range(len(a)):
if(a[i] == elemToReplace):
a[i] = substitutionElem
return a
#<Best Code>
def arrayReplace(i, e, s):
return [x if x!=e else s for x in i]
26. Check if all digits of the given integer are even.
[Example]
|
[Solution]
#<My Code>
def evenDigitsOnly(n):
s = str(n)
for c in s:
if int(c) % 2 == 0: continue
else: return False
return True
#<Best Code>
def evenDigitsOnly(n):
return all([int(i)%2==0 for i in str(n)])
27. Correct variable names consist only of English letters, digits and underscores and they can't start with a digit.
Check if the given string is a correct variable name.
[Example]
|
[Solution]
#<My Code>
def variableName(name):
s = name
if s[0].isdigit(): return False
for c in s:
if c.isdigit() or c.isalpha() or c == '_': continue
else: return False
return True
#<Best Code>
def variableName(name):
return name.isidentifier()
#<Best Code2>
def variableName(name):
if re.match('[a-z_][0-9_a-z]*$', name,re.IGNORECASE):
return True
return False
'Python > CodeSignal Algorithm' 카테고리의 다른 글
[Python] CodeSignal 문제 풀이 (31~33) (0) | 2020.03.12 |
---|---|
[Python] CodeSignal 문제 풀이 (28~30) (0) | 2020.03.12 |
[Python] CodeSignal 문제 풀이 (22~24) (0) | 2020.03.12 |
[Python] CodeSignal 문제 풀이 (19~21) (0) | 2020.03.12 |
[Python] CodeSignal 문제 풀이 (16~18) (0) | 2020.03.12 |