简体   繁体   中英

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM