[Python] CodeSignal 문제 풀이 (19~21)

2020. 3. 12. 20:52Python/CodeSignal Algorithm

19. Call two arms equally strong if the heaviest weights they each are able to lift are equal.

Call two people equally strong if their strongest arms are equally strong (the strongest arm can be both the right and the left), and so are their weakest arms.

Given your and your friend's arms' lifting capabilities find out if you two are equally strong.

 

[Example]

  • For yourLeft = 10, yourRight = 15, friendsLeft = 15, and friendsRight = 10, the output should be
    areEquallyStrong(yourLeft, yourRight, friendsLeft, friendsRight) = true;
  • For yourLeft = 15, yourRight = 10, friendsLeft = 15, and friendsRight = 10, the output should be
    areEquallyStrong(yourLeft, yourRight, friendsLeft, friendsRight) = true;
  • For yourLeft = 15, yourRight = 10, friendsLeft = 15, and friendsRight = 9, the output should be
    areEquallyStrong(yourLeft, yourRight, friendsLeft, friendsRight) = false.

 

[Solution]

#<My Code>
def areEquallyStrong(yourLeft, yourRight, friendsLeft, friendsRight):
    return True if (yourLeft == friendsLeft and yourRight == friendsRight) or (yourLeft == friendsRight and yourRight == friendsLeft) else False
    
#<Best Code>
def areEquallyStrong(yourLeft, yourRight, friendsLeft, friendsRight):
    return {yourLeft, yourRight} == {friendsLeft, friendsRight}

 

20. Given an array of integers, find the maximal absolute difference between any two of its adjacent elements.

 

[Example]

For inputArray = [2, 4, 1, 0], the output should be
arrayMaximalAdjacentDifference(inputArray) = 3.

 

[Solution]

#<My Code>
def arrayMaximalAdjacentDifference(inputArray):
    arr = inputArray
    return max(abs(arr[i] - arr[i+1]) for i in range(len(arr) - 1))

#<Best Code>
def arrayMaximalAdjacentDifference(a):
    diffs=[abs(a[i]-a[i+1]) for i in range(len(a)-1)]
    return max(diffs)

 

21. An IP address is a numerical label assigned to each device (e.g., computer, printer) participating in a computer network that uses the Internet Protocol for communication. There are two versions of the Internet protocol, and thus two versions of addresses. One of them is the IPv4 address.

 

[Example]

 

 

[Solution]

#<My Code>
def isIPv4Address(inputString):
    s = inputString
    arr = s.split('.')
    
    if(s.count('.') != 3):
        return False
    
    for i in range(len(arr)):
        if(arr[i].isdigit()):
            iArr = int(arr[i])
            if(0 <= iArr and iArr <= 255): continue
            else: return False
        else:
            return False
    return True
    
#<Best Code>
def isIPv4Address(s):
    p = s.split('.')

    return len(p) == 4 and all(n.isdigit() and 0 <= int(n) < 256 for n in p)