728x90
반응형

Summary

이 문제는 List Comprehensions 를 통해 풀어보라고 내준 문제인 것으로 보였다.
그래서 List Comprehensions 에 대해서 먼저 알아야할 필요가 있었다.

 

List Comprehensions 에 대해서 간단하게 정리하고 넘어가자면
리스트를 보다 쉽게 만들기 위한 방법이라고 생각하면 된다.

 

예를 들어, 이 문제를 풀기 위해서 반복문을 통해 문제를 풀어보았다.

result = []

for i in range(0, x+1):
    for j in range(0, y+1):
        for k in range(0, z+1):
            if i+j+k != n:
                result.append([i,j,k])

이렇게 반복문을 통해 리스트를 만들어도 해결할 수 있지만 List Comprehensions 를 통해 보다 쉽게 만들 수 있다.

result = [[i, j, k] for i in range(0, x+1) for j in range(0, y+1) for k in range(0, z+1) if i+j+k!=n]

 

보다시피 여러 반복문을 한 줄로 줄여서 리스트를 쉽게 만들 수 있었고
List Comprehensions 문법을 사용해서 문제를 풀 수 있었다.

 

Problem

Let's learn about list comprehensions! You are given three integers  and  representing the dimensions of a cuboid along with an integer . Print a list of all possible coordinates given by  on a 3D grid where the sum of  is not equal to . Here, . 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 n = 3 .

[[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.

Sample Input 0

1
1
1
2

Sample Output 0

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

Explanation 0

Each variable  and  will have values of 0 or 1. All permutations of lists in the form .
[i,j,k] = [[0, 0, 0], [0, 0, 1], [0, 1, 0], [1, 0, 0], [1, 1, 1]].
Remove all arrays that sum to n = 2 to leave only the valid permutations.

 

Submit Code

if __name__ == '__main__':
    x = int(input())
    y = int(input())
    z = int(input())
    n = int(input())
    
    result = []
    
    # for i in range(0, x+1):
    #     for j in range(0, y+1):
    #         for k in range(0, z+1):
    #             if i+j+k != n:
    #                 result.append([i,j,k])
    
    result = [[i, j, k] for i in range(0, x+1) for j in range(0, y+1) for k in range(0, z+1) if i+j+k!=n]
                    
    print(result)

 

 

Result

 

728x90
반응형
복사했습니다!