
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Flipping an Image in Python
Suppose we have a binary matrix A, this is the representation of an image, we want to flip the image horizontally, after that invert it, and finally return the resulting image. To flip the image horizontally each row of the image will be reversed. And to invert the image each 0 will be replaced by 1, and each 1 will be replaced by 0.
So, if the input is like
1 | 1 | 0 |
1 | 0 | 1 |
0 | 0 | 0 |
then the output will be
1 | 0 | 0 |
0 | 1 | 0 |
1 | 1 | 1 |
To solve this, we will follow these steps −
- result:= a new list
- for each row i in A, do
- Reverse:= reverse row i
- for j in range 0 to size of Reverse, do
- if Reverse[j] is same as 1, then
- Reverse[j]:= 0
- otherwise,
- Reverse[j]:= 1
- if Reverse[j] is same as 1, then
- insert Reverse at the end of result
- return result
Let us see the following implementation to get better understanding −
Example
class Solution: def flipAndInvertImage(self, A): result=[] for i in A: Reverse=i[::-1] for j in range(len(Reverse)): if Reverse[j]==1: Reverse[j]=0 else: Reverse[j]=1 result.append(Reverse) return result ob = Solution() print(ob.flipAndInvertImage([[1,1,0],[1,0,1],[0,0,0]]))
Input
[[1,1,0],[1,0,1],[0,0,0]]
Output
[[1, 0, 0], [0, 1, 0], [1, 1, 1]]
Advertisements