Python Exercise 21: list comprehensions

mathewchan

HHMathewChan

Posted on July 5, 2022

Python Exercise 21: list comprehensions

Question

You are given three integers (x,y,z) representing the dimensions of a cuboid along with an integer n .

  • Print a list of all possible coordinates
    • given by  (i, j , k) in a 3D grid
    • where the sum of  i+j+k is not equal to n.
    • i.e. can be greater than or smaller than n
  • Here 0<=i<=x; 0<=j<=y; 0<=k<=z
  • Please use list comprehensions
  • Print the list in lexicographic increasing order.

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]]
Enter fullscreen mode Exit fullscreen mode
  • Print an array of the elements that sum of i, j, k does not equal to n (The required output)
[[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]]
Enter fullscreen mode Exit fullscreen mode

My solution

  • code
    # make list of all x,y and z possible number
    x = int(input())
    y = int(input())
    z = int(input())
    n = int(input())
    x = [i for i in range(x+1)]
    y = [i for i in range(y+1)]
    z = [i for i in range(z+1)]
    # for each combination of i,j,k will form a sublist in the final_list, and sum of i,j,k will not equal to n
    final_list = [[i,j,k]for i in x for j in y for k in z if (i+j+k)!=n]
    print(final_list)
Enter fullscreen mode Exit fullscreen mode

Other solution

  • a shorter version
x = int(input())
y = int(input())
z = int(input())
n = int(input())
# for each combination of i,j,k will form a sublist in the final_list, and sum of i,j,k will not equal to n
final_list = [[i,j,k]for i in range(x+1) for j in range(y+1) for k in range(z+1) if (i+j+k)!=n]
print(final_list)
Enter fullscreen mode Exit fullscreen mode

My reflection

  • The first time to try problem need to obtain variable form standard input
  • good exercise.
  • The first time to use multiple for loop in list comprehension.

Credit

challenge on hackerrank

💖 💪 🙅 🚩
mathewchan
HHMathewChan

Posted on July 5, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related