HackerRank Python: List Comprehensions Solution

Table of Contents

Question

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 (ijk) 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 [ijk 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 xyz 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 xy and z will have values of 0 or 1. All permutations of lists in the form [ijk] = [[0, 0, 0], [0, 0, 1], [0, 1, 0], [0, 1, 1], [1, 0, 0], [1, 0, 1],  [1, 1, 0]].

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

				
					if __name__ == '__main__':
    x = int(input("Enter the value of x: "))
    y = int(input("Enter the value of y: "))
    z = int(input("Enter the value of z: "))
    n = int(input("Enter the value of n: "))
    output = []
    abc = []
    for X in range(x + 1):
        for Y in range(y + 1):
            for Z in range(z + 1):
                if X + Y + Z != n:
                    abc = [X, Y, Z]
                    output.append(abc)
    print("Output:", output)

				
			

In this code, the program prompts the user to enter the values of x, y, z, and n. It then initializes an empty list called output and an empty list called abc. The program then uses nested for loops to iterate through all possible combinations of X, Y, and Z within their respective ranges (from 0 to x, y, and z inclusive). If the sum of X, Y, and Z is not equal to n, the current values of X, Y, and Z are stored in the list abc and appended to the output list. Finally, the output list is printed

If you find anything wrong in this Solution, feel free to reach us in the comment section.

Sharing Is Caring:

Leave a Comment