{ }codelper
comprehensions2D listsP0083

Flip and filter a grid

You are given an integer grid with r rows and c columns.
Using comprehensions instead of loops, build and print these three things. 1) The flipped grid: the j-th column of the original (top to bottom) becomes the j-th row of the new grid.
Print c lines with r numbers each, separated by single spaces. 2) Squares of multiples of 3: read the grid from the top row down, and left to right within a row, keep only the multiples of 3 (including 0 and negatives) and square them.
Print the count k first, then the k squares in reading order, all on one line separated by spaces.
If there are none, print just 0. 3) Print the number of distinct values in the grid.

Input
First line r c, then r lines of c integers.
1 ≤ r, c ≤ 50, -1000 ≤ value ≤ 1000
Output
c lines of the flipped grid, then a line with k and the k squares, then a line with the number of distinct values
Example 1 · stdin
2 3
1 3 -6
4 9 3
stdout
1 4
3 9
-6 3
4 9 36 81 9
5
main.py
Input (stdin)

When you run, these lines are fed to input()/stdin in order (the program doesn't stop to ask).

$ Ready

Open this on a computer to write and run code. On mobile you can read the problem and the solutions.

In other languagesShow solutions by language · 1 languages

This problem takes Python only.
List and set comprehensions are Python syntax; other languages do the same job with loops, map/filter (JS), streams (Java) or LINQ (C#).
The for clauses in a comprehension go in the same order as nested loops: in [x * x for row in grid for x in row if x % 3 == 0] the outer for row comes first.
Swap them to walk columns first and the flattened order changes.
Flipping is a nested comprehension, [[row[j] for row in grid] for j in range(c)] (or zip(*grid)); building the cells first with [[0] * r] * c puts the same row in c times, so every row comes out identical.
With parentheses instead of brackets, (x for row in grid for x in row) is a generator: once used up, a second pass sees nothing (the distinct count becomes 0).
In Python -6 % 3 is 0, so negative multiples are kept correctly.
In Craykon you would build it with a foreach (x in row) loop and Add.

Pythonmain.py · 14 lines
r, c = map(int, input().split())grid = [[int(x) for x in input().split()] for _ in range(r)] # 1) 뒤집기: 열 j를 줄로 — 바깥 내포가 새 줄, 안쪽 내포가 그 줄의 칸flipped = [[row[j] for row in grid] for j in range(c)]for line in flipped:    print(" ".join(str(x) for x in line)) # 2) 펼치며 거르기: for를 읽는 차례(위 줄 → 그 줄의 칸) 그대로 적는다squares = [x * x for row in grid for x in row if x % 3 == 0]print(len(squares), *squares) # 3) 집합 내포: 서로 다른 값의 개수print(len({x for row in grid for x in row}))