Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Check if it is possible to create a palindrome string from given N in Python
Suppose we have a number n. We have to check whether we can create an alphabetical lowercase string from that number and check whether the string is palindrome or not. Here we will take only characters from a to j, where a = 0, b = 1... j = 9. So if the number is 42, the substring "ec" will be repeated till we reach 6 (4+2) characters "ececec", then check if this is palindrome or not.
So, if the input is like n = 43, then the output will be True. The string is "ededede" and this is palindrome.
Algorithm
To solve this, we will follow these steps ?
- temp := blank string
- s := n as string
- letters := all characters from a to j
- sum := 0
- substr := blank string
- for each digit in s, do
- d := digit as numeric
- substr := substr concatenate letters[d]
- sum := sum + d
- while length of temp <= sum, do
- temp := temp concatenate substr
- temp := temp[from index 0 to sum − 1]
- return true when temp is palindrome, otherwise false
Example
Let us see the following implementation to get better understanding ?
def isPalindrome(s):
return s == s[::-1]
def solve(n):
temp = ""
s = str(n)
letters = "abcdefghij"
digit_sum = 0
substr = ""
for i in range(len(s)):
d = int(s[i])
substr += letters[d]
digit_sum += d
while len(temp) <= digit_sum:
temp += substr
temp = temp[:digit_sum]
return isPalindrome(temp)
# Test the function
n = 43
print(solve(n))
The output of the above code is ?
True
How It Works
For n = 43:
- Digits: 4, 3
- Corresponding letters: 'e', 'd'
- Substring: "ed"
- Sum of digits: 4 + 3 = 7
- Repeat "ed" to get 7 characters: "ededede"
- Check palindrome: "ededede" == "ededede" ? True
Additional Example
Let's test with another number ?
def isPalindrome(s):
return s == s[::-1]
def solve(n):
temp = ""
s = str(n)
letters = "abcdefghij"
digit_sum = 0
substr = ""
for i in range(len(s)):
d = int(s[i])
substr += letters[d]
digit_sum += d
while len(temp) <= digit_sum:
temp += substr
temp = temp[:digit_sum]
return isPalindrome(temp)
# Test with different numbers
test_numbers = [42, 43, 11, 20]
for num in test_numbers:
result = solve(num)
print(f"n = {num}, Result: {result}")
The output of the above code is ?
n = 42, Result: False n = 43, Result: True n = 11, Result: True n = 20, Result: False
Conclusion
This algorithm converts digits to letters, creates a repeating pattern, and checks if the resulting string of specified length is a palindrome. The key insight is mapping digits 0-9 to letters 'a'-'j' and using the sum of digits as the target string length.
---