HackerRank List Comprehensions solution

List Comprehensions solution

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. You have to 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
    Input Format
    Four integers X, Y, Z and N each on four separate lines, respectively.

    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 x, y and z 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], [0, 1, 1], [1, 0, 0], [1, 0, 1], [1, 1, 0], [1, 1, 1]].
    Remove all arrays that sum to n = 2 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]]

Solution in Python3

				
					x,y,z,n = [int(input()) for i in range(4)]
print([[i,j,k] 
for i in range(x+1) for j in range(y+1) for k in range(z+1) if ((i+j+k) != n)])

				
			
Thank You For Visiting Our Website!
This Post is referred by hackerRank you can check the code on hackerRank.
Please Visit : Repeated String – Code-Tech Community
And make sure to leave us a comment down below , we will be happy to know if this worked for you.
Happy Coding Mates ! 🙂

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Shopping Cart