[Python] CodeSignal 문제 풀이 (25~27)

2020. 3. 12. 21:05Python/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]

  • For n = 248622, the output should be
    evenDigitsOnly(n) = true;
  • For n = 642386, the output should be
    evenDigitsOnly(n) = false.

 

[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]

  • For name = "var_1__Int", the output should be
    variableName(name) = true;
  • For name = "qq-q", the output should be
    variableName(name) = false;
  • For name = "2w2", the output should be
    variableName(name) = false.

 

[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