[Python] CodeSignal 문제 풀이 (13~15)

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

13. Write a function that reverses characters in (possibly nested) parentheses in the input string. Input strings will always be well-formed with matching ()s.

 

[Example]

  • For inputString = "(bar)", the output should be
    reverseInParentheses(inputString) = "rab";
  • For inputString = "foo(bar)baz", the output should be
    reverseInParentheses(inputString) = "foorabbaz";
  • For inputString = "foo(bar)baz(blim)", the output should be
    reverseInParentheses(inputString) = "foorabbazmilb";
  • For inputString = "foo(bar(baz))blim", the output should be
    reverseInParentheses(inputString) = "foobazrabblim".
    Because "foo(bar(baz))blim" becomes "foo(barzab)blim" and then "foobazrabblim".

 

[Solution]

..

 

 

14. Several people are standing in a row and need to be divided into two teams. The first person goes into team 1, the second goes into team 2, the third goes into team 1 again, the fourth into team 2, and so on.

You are given an array of positive integers - the weights of the people. Return an array of two integers, where the first element is the total weight of team 1, and the second element is the total weight of team 2 after the division is complete.

 

[Example]

For a = [50, 60, 60, 45, 70], the output should be
alternatingSums(a) = [180, 105].

 

[Solution]

def alternatingSums(a):
    team = [0, 0]
    for i in range(len(a)):
        if(i % 2 == 0):
            team[0] += a[i]
        else:
            team[1] += a[i]
    print(team)
    return team

 

15. Given a rectangular matrix of characters, add a border of asterisks(*) to it.

 

[Example]

[Solution]

	<My Code>
def addBorder(picture):
    low = len(picture)
    wall = "*" * (len(picture[0]) + 2)
    border = []
    for i in range(low + 2):
        if (i == 0):border.append(wall)
        elif(i == low + 1): border.append(wall)
        else: border.append("*" + picture[i - 1] + "*")
    return border
   
   
	<BestCode>
def addBorder(picture):
    l=len(picture[0])+2
    return ["*"*l]+[x.center(l,"*") for x in picture]+["*"*l]