You are going to be given an array of integers. Your job is to take that array and find an index N where the sum of the integers to the left of N is equal to the sum of the integers to the right of N. If there is no index that would make this happen, return -1.
test.assert_equals(find_even_index([1,2,3,4,3,2,1]),3)
위 문제를 보면 3번째 인덱스에 위치할 때 인덱스 왼쪽의 수들의 합과 오른쪽 수들의 합이 일치한다. 만약 그 값이 없다면 -1을 리턴하면 된다.
def find_even_index(arr): for i in range(len(arr)): if sum(arr[:i]) == sum(arr[i+1:]): return i return -1
i번째까지의 arr의 합이 i 다음 인덱스부터 마지막까지의 합이 일치한다면 i를 리턴하고 그렇지 않으면 -1을 리턴하는 문제이다.
두번째는
solution('abc') # should return ['ab', 'c_']
solution('abcdef') # should return ['ab', 'cd', 'ef']
즉 문자열이 짝수이면 두개씩 끊어서 배열, 아니라면 마지막 홀수로 끝나는 인덱스에 _를 추가해야 한다.
def solution(s): el = [] a = '' for i in s: a +=i if len(a) == 2: el.append(a) a = '' if a: el.append(a + '_') return el
빈 리스트와 문자열을 만든 후 a 안에 문자열의 0번째 인덱스부터 넣어준다. a의 길이가 2라면 빈 리스트에 추가하고 다시 a는 빈 문자열이 된다. 그리고 위 for문이 종료되고 만약 a가 빈 문자열이 아닌 알파벳이 존재한다면 거기에다 _를 더해준 후 리스트에 더해준다.