
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
Find All Upside-Down Numbers of Length n in Python
Suppose we have a value n. We have to find all upside down numbers of length n. As we knot the upside down number is one that appears the same when flipped 180 degrees.
So, if the input is like n = 2, then the output will be ['11', '69', '88', '96'].
To solve this, we will follow these steps −
Define a function middle() . This will take x
-
if x is 0, then
return list of a blank string
-
if x is same as 1, then
return a new list of elements 0, 1, 8
ret := a new list
mid := middle(x − 2)
-
for each m in mid, do
-
if x is not same as n, then
insert ("0" concatenate m concatenate "0") at the end of ret
insert ("1" concatenate m concatenate "1") at the end of ret
insert ("6" concatenate m concatenate "9") at the end of ret
insert ("8" concatenate m concatenate "8") at the end of ret
insert ("9" concatenate m concatenate "6") at the end of ret
-
return ret
From the main method, do the following −
-
if n is 0, then
return a new list
otherwise return sorted list of middle(n)
Let us see the following implementation to get better understanding −
Example
class Solution: def solve(self, n): if not n: return [] def middle(x=n): if not x: return [""] if x == 1: return list("018") ret = [] mid = middle(x - 2) for m in mid: if x != n: ret.append("0" + m + "0") ret.append("1" + m + "1") ret.append("6" + m + "9") ret.append("8" + m + "8") ret.append("9" + m + "6") return ret return sorted(middle()) ob = Solution() print(ob.solve(2))
Input
2
Output
['11', '69', '88', '96']