[Python 문제풀이] 9일차

2020. 7. 17. 11:0003. Resources/Python

728x90
반응형

Day_9

Intro

Q14. alternatingSums

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.

def alternatingSums(a):
    team1 = 0
    team2 = 0
    for i in range(len(a)):
        if i % 2 == 0: # 2로 나눈 나머지가 0인 경우
            team1 += a[i]
        else: # 2로 나눈 나머지가 1인 경우
            team2 += a[i]

    Sums = list()
    Sums.append(team1)
    Sums.append(team2)

    return Sums

처음에 리스트로 만들어서 합산을 하려고 했는데, 굳이 리스트 없이 홀수끼리의 합과 짝수끼리의 합을 구해서 배열에 넣고 리턴하면 되는 것이었다. 복잡하게 생각할 필요 없었던 문제

Q15. Add Border

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

def addBorder(picture):

    border = "*"*(len(picture[0])+2)

    for i in range(len(picture)):
        picture[i] = "*"+picture[i]+"*"

    picture.insert(0,border)
    picture.append(border)

    return picture

작성 흐름

# 테스트 케이스
picture = ["abc",
           "ded"]

# 테스트 케이스 출력해보기
print(picture)
# 첫 단어의 사이즈 확인해보기
print(picture[0])
# string 자료형의 경우 문자열을 더하여 문자열을 늘릴 수 있음
print("*" + picture[0] + "*")

# 위 아래 테두리 형태 만들기
border = "*"*(len(picture[0])+2)

# 기존 단어에 테두리 추가하기
for i in range(len(picture)):
    picture[i] = "*"+picture[i]+"*"

# 테두리가 추가된 입력에 위아래 테두리 추가하기
picture.insert(0,border)
picture.append(border)

# 출력해서 확인
print(picture)
반응형

'03. Resources > Python' 카테고리의 다른 글

[Python 문제풀이] 11일차  (0) 2020.07.19
[Python 문제풀이] 10일차  (0) 2020.07.18
[Python 문제풀이] 8일차  (0) 2020.07.16
[Python 문제풀이] 7일차  (0) 2020.07.15
[Python 문제풀이] 6일차  (0) 2020.07.14