HackerRank List Comprehensions Solution In Python

In this post, I shall bring the solution to the HackerRank List Comprehensions Solution In Python with the explanation of each line.

Problem

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

1112

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.

Solution To HackerRank List Comprehenhension in Python

Hackerrank List Comprehension Solution

Since the problem is to improve your knowledge of List Comprehension, I will be the answer in list comprehension and an alternative method for the sake of explanation.

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

Alternative Solution

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

Code Explanation

List comprehensions in Python are concise, syntactic constructs. They can be utilized to generate lists from other
lists by applying functions to each element in the list.

The for expressions set i, j and k to each value in the ranges from 0 to x, y and z.

The first for expression sets i to each value from range of 0 to x. The second for expression sets j to each value from range of 0 to y while the third for expression sets k to each value from range of 0 to z.

for i in range(x + 1)

The If statement before the print is serving as a filter that if the sum of all i, j, k in a list of the lists formed is equal to n, it shouldn’t be assigned.

if sum([i, j, k]) != n

Thanks for reading.

Comments