티스토리 뷰

728x90

List Comprehensions

Let's learn about list comprehensions! You are given three integers x, y and z representing the dimensions of a cuboid along with an integer n. Print a list of all possible coordinates given by (i, j, k) on a 3D grid where the sum of i + j + k is not equal to n. Here, 0 <= i <= x; 0 <= j <=y; 0 <= k <= z. Please use list comprehensions rather than multiple loops, as a learning exercise.

Example
x = 1
y = 1

z = 2

n = 3

 

All permutations of [i, j, k] are:

[[0,0,0], [0,0,1], [0,0,2], [0,1,0], [0,1,1], [0,1,2], [1,0,0], [1,0,1], [1,0,2], [1,1,0], [1,1,1], [1,1,2]].

 

Print an array of the elements that do not sum to .

[[0,0,0], [0,0,1], [0,0,2], [0,1,0], [0,1,1], [1,0,0], [1,0,1], [1,1,0], [1,1,2]]

 

Input Format

Four integers x,y,z and n, each on a separate line.

Constraints

Print the list in lexicographic increasing order.

 

문제해석

1. x, y, z는 정육면체의 각 차원이라고 한다.

2. x, y, z로 가능한 조합인 (i, j, k)를 구해야 하는데 2가지의 제약조건이 있다.

3. 제약조건 1번째로 i+j+k != n 이어야 한다. (n는 이 때 말고는 다른데서 사용되지 않는다.)

4. 제약조건 2번째로 i <= x, j <= y, k <= z 이어야 한다. (0보다 크다 조건은 사용하지 않아도 테스트는 통과한다.)

 

문제풀이

처음에 영어해석을 못해서 한참 고생했다..; 번역기 돌려보니 순열이라는 식으로 번역이 되어서 한참 수학공부도 하고...ㅠ.ㅠ 아무튼 순열과는 좀 다른듯 하다. 0 값이 들어가야 하는 부분이 특히 그렇다. 

파이썬도 처음 해보다 보니 range() 함수 안에 값이 포함되지 않는다는 것도 몰랐다..; 그냥 +1을 해주었다. 

문제 제목에서 힌트를 얻어서 list의 append() 함수를 찾아서 사용하였다. 

Discussions의 코드도 다들 비슷하게 푼 것 같다. 

if __name__ == '__main__':
    x = int(input())
    y = int(input())
    z = int(input())
    n = int(input())
    
    # print("x:{0}, y:{1}, z:{2}, n:{3}\n".format(x,y,z,n))
    retList = []
    templist = []
    i = 0
    j = 0
    k = 0    
    
    for i in range(x+1):
        for j in range(y+1):
            for k in range(z+1):
                if i+j+k != n:
                    templist = [i, j, k]
                    retList.append(templist)
                    
    print(retList)

이게 easy야??!!

 

 

728x90
LIST
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
글 보관함