List Comprehensions in Python - Hacker Rank Solution

Problem

Let's learn about list comprehensions! You are given three integers x and y 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. Please use list comprehensions rather than multiple loops, as a learning exercise.


Example

x=1

y=1

z=2

n=3

All permutations of  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  and , 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  or . All permutations of lists in the form .

Remove all arrays that sum to  to leave only the valid permutations.


Sample Input 1

2
2
2
2


Sample Output 1

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


How to solve this problem? [Explanation of this problem statement]

  1. The problem states that we have to find out all the possible coordinates under the given condition.
  2. So, our first task is to make all the possible combination of coordinate by using input(x,y,z).
  3. Then now, we iterate the for loop that limits is taken from the input and again we iterate the nested loop for y and z. 
  4. Now, we check that the sum of the coordinated is must not equal to the n(the number given by the user from input).
  5. Now, we append the remaining combination of the coordinates to the lists, And finally print the lists.  


Solution

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
if __name__ == '__main__':
    x = int(input())
    y = int(input())
    z = int(input())
    n = int(input())
    
    lists = []
    
    for i in range(x+1):
        for j in range(y+1):
            for k in range(z+1):
                if (i+j+k)!=n:
                    lists.append([i,j,k])
                
                    
    print(lists)
Next Post Previous Post
No Comment
Add Comment
comment url