PitchMod
PitchMod

Reputation: 25

List Comprehensions and Loops

I'm currently going through different Python3 challenges on Hackerrank and I ran into this problem that caught me off guard. I found the solution but I'm having trouble wrapping my mind around how it works. I'm familiar with loops in python but I can't seem to trace the code step by step.

Problem

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 on a 3D grid where the sum of is not equal to N.

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

1
1
1
2

Sample Output

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

Solution

x, y, z, n = (int(input()) for _ in range(4))
print([[a, b, c] for a in range(x+1) for b in range(y+1) for c in range(z+1) if a + b + c != n])

Upvotes: 0

Views: 1153

Answers (1)

Rushabh Mehta
Rushabh Mehta

Reputation: 1559

Let's think about how list comprehensions work.

The list comprehension you've posted works like the following loops:

l = []
for a in range(x):
    for b in range(y):
        for c in range(z):
            if a+b+c!= n:
                l.append([a,b,c])
print(l)

So, we loop across all possible values of a,b,and c, and find the triplets that satisfy our condition.

Upvotes: 2

Related Questions