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.
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 .
Four integers X, Y, Z, and N each on four separate lines, respectively.
Print the list in lexicographic increasing order.
1
1
1
2
[[0, 0, 0], [0, 0, 1], [0, 1, 0], [1, 0, 0], [1, 1, 1]]
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.