[Python] CodeSignal 문제 풀이 (52~54)

2020. 4. 14. 17:05Python/CodeSignal Algorithm

 

 

 

52. Define a word as a sequence of consecutive English letters. Find the longest word from the given string.

 

[Example]

For text = "Ready, steady, go!", the output should be
longestWord(text) = "steady".

 

[Solution]

#<My Code>
def longestWord(text):
    l = list()
    print(ord("a"), ord("z"), ord("A"), ord("Z"))

    s = ""
    for i in range(len(text)):
        if 97 <= ord(text[i]) and ord(text[i]) <= 122 or 65 <= ord(text[i]) and ord(text[i]) <= 90:
            s += text[i]
        else:
            l.append(s)
            s = ""
    l.append(s)
    return max(l, key=len)

#<Best Code>
def longestWord(text):
    return max(re.split('[^a-zA-Z]', text), key=len)

 

 

53. Check if the given string is a correct time representation of the 24-hour clock.

 

[Example]

  • For time = "13:58", the output should be
    validTime(time) = true;
  • For time = "25:51", the output should be
    validTime(time) = false;
  • For time = "02:76", the output should be
    validTime(time) = false.

 

[Solution]

#<My Code>
def validTime(time):
    l = time.split(':')
    
    if int(l[0]) < 24 and int(l[1]) < 60:
        return True
    else:
        return False

#<Best Code>
def validTime(time):
    h,m=map(int,time.split(":"))
    return 0<=h<24 and 0<=m<60

 

 

54. CodeMaster has just returned from shopping. He scanned the check of the items he bought and gave the resulting string to Ratiorg to figure out the total number of purchased items. Since Ratiorg is a bot he is definitely going to automate it, so he needs a program that sums up all the numbers which appear in the given input.

Help Ratiorg by writing a function that returns the sum of numbers that appear in the given inputString.

 

[Example]

For inputString = "2 apples, 12 oranges", the output should be
sumUpNumbers(inputString) = 14.

 

[Solution]

#<My Code>
def sumUpNumbers(inputString):
    l = re.findall('\d+', inputString)
    sumUp = 0

    for n in l:
        sumUp += int(n)
    return sumUp

#<Best Code>
def sumUpNumbers(inputString):
    l = re.findall(r'\d+', inputString)
    return sum(int(n) for n in l)