Today we are going to learn about the palindrome series and how to implement and identify a palindrome in Python. So let’s dive right into it!
What is a Palindrome?
A number is defined as a Palindrome number if it reads the exact same from both forward and backward. And the crazy thing is that it is not only valid to numbers. Even if a string reads the same forwards and backward, then it is a Palindrome as well!
Let us look at some examples to understand it better.
What is a Palindrome series?
1. Palindrome Numbers
Let us consider two numbers: 123321 and 1234561.
The first number 123321, when read forward and backward is the same number. Hence it is a palindrome number.
On the other hand, 1234561, when reading backward is 1654321 which is definitely not the same as the original number. Hence, it is not a Palindrome Number.
2. Palindrome Strings
The logic that was explained for the Palindrome Numbers is also applicable to the strings. Let’s consider two basic strings: aba and abc.
String aba reads the same no matter how it is read (backward or forward). But on the other hand string abc when reading backward results in cba which is not same as the original string.
Hence aba is a Palindrome while abc isn’t.
How to verify for Palindrome?
1. Palindrome Numbers
To check if a number is a Palindrome number or not, we first take the input of the number and create a copy of the number taken as an input.
We then create a new variable to store the reversed number and initialize it with 0.
Traverse through the number using mod 10 and division by 10 operations and in each loop make sure to add the digit in the reversed number variable*10.
2. Palindrome Strings
To check for a string, we take a string as input and calculate its length. We also initialize an empty string to store the reverse of the string.
We create a decrementing loop starting from the last index and going to the first and each time concatenate the current reversed string with the new letter obtained.
Pseudo-code to implement Palindrome in Python
1. Palindrome Numbers
READ n CREATE A COPY OF n as c_n CREATE r_v = 0 ( to store reversed number) WHILE n!=0: d=n%10 r_v=r_v*10+d n=n/10 if(c_n == r_v): print "PALINDROME" else: print "NOT PALINDROME"
2. Palindrome Strings
READ s CALCULATE length of s l_s CREATE r_s = "" ( to store reversed string) FOR i: l_s-1 -> 0 r_s + = s[i] if(r_s == s): PRINT "PALINDROME" else: PRINT "NOT PALINDROME"
Code to implement Palindrome Checking in Python
Now that you know what Palindromes are and how to deal with them in the case of strings and numbers, let me show you the code for both.
1. Palindrome Implementation: Numbers
Let’s check for palindrome numbers using Python.
n = input() n = int(n) copy_n=n result = 0 while(n!=0): digit = n%10 result = result*10 + digit n=int(n/10) print("Result is: ", result) if(result==copy_n): print("Palindrome!") else: print("Not a Palindrome!")
2. Palindrome Implementation: Strings
Let’s now check for Palindrome strings in Python
s = input() l_s=len(s) r_s="" for i in range(l_s-1,-1,-1): r_s+=s[i] print("Reuslt is: ",r_s) if(r_s==s): print("PALINDROME") else: print("NOT PALINDROME")
Palindrome Numbers
123321 Result is: 123321 Palindrome!
Palindrome Strings
aibohphobia Reuslt is: aibohphobia PALINDROME
Conclusion
Congratulations! Today in this tutorial you learned about Palindromes and how to implement them as well! Hope you learned something! Thank you for reading!
Палиндром в Python – это число или буква, которые остаются неизменными, даже если число и буквы перевернуты.
Например:
121, 11, 414, 1221, 74747 – числа палиндрома.
MOM, DAD, MADAM, REFER – это буквы палиндрома.
JAVATPOINT, PROGRAM, JAVA – это не буквы палиндрома.
Алгоритм палиндрома
- Прочтите цифру или букву.
- Сохраните букву или цифру во временной переменной.
- Переверните букву или цифру.
- Сравните временную переменную с обратной буквой или цифрой.
- Если обе буквы или цифры совпадают, выведите «эта строка / число является палиндромом».
- Иначе напишите «эта строка / число не является палиндромом».
Примеры программ палиндрома на Python:
Программа 1: строка палиндрома
str = 'JaVaJ' str = str.casefold() # This string is reverse. rev = reversed(str) if list(str) == list(rev): print("PALINDROME !") else: print("NOT PALINDROME !")
Выход:
PALINDROME !
Программа 2: строчная программа палиндрома
string=input(("Enter a letter:")) if(string==string[::-1]): print("The letter is a palindrome") else: print("The letter is not a palindrome")
Выход:
Enter a letter: javatpoint The letter is not a palindrome Enter a letter: MADAM The letter is a palindrome
Программа 3: числовая программа-палиндром с использованием цикла while
Num = int(input("Enter a value:")) Temp = num Rev = 0 while(num > 0): dig = num % 10 rev = rev * 10 + dig num = num // 10 if(temp == rev): print("This value is a palindrome number!") else: print("This value is not a palindrome number!")
Выход:
Enter the value: 2551 This value is not a palindrome number! Enter the value: 1221 This value is a palindrome number!
Изучаю Python вместе с вами, читаю, собираю и записываю информацию опытных программистов.
Do you know what is palindrome? In this Python tutorial, we will understand how to write a Python Program to check if it is a palindrome or not. Also, we are going to cover the below topics.
- Write a Python Palindrome program string
- Write a Python Palindrome program number
- Write a Python Palindrome program using loop
- Write a Python Palindrome program using recursion
- How to write a longest Palindrome Python program
- Python program for palindrome or not
- Write a Python program to check if it is palindrome or not
- How to write a palindrome program in python without using the string function
- Write a palindrome program in python using the reverse function
- Write a Python Program to print palindrome numbers between 1 to 100
- Python Program to find palindrome word
- Write a palindrome program in python using a while loop
- Write a palindrome program in python using if else
- Write a palindrome program in python using slicing
- Write a palindrome program in python using a list
- Any number or string that remains unchanged when reversed is known as a palindrome.
- A palindrome is a word or a set of numbers made up of letters that spell the same word when reading both forward and backward. Python Palindrome permits punctuation, symbols, letters, and spaces within the Palindrome words.
- It works by comparing the actual word and the reverse of the word, and if there is an exact match, the matched value is True. Python has three different forms of palindrome methodology: number palindrome, multiple-word palindrome, and single-word palindrome.
- For example, “mom” is the same in forwarding or reverse direction.
Example:
new_val=input(("Enter a string:"))
if(new_val==new_val[::-1]):
print("String is a palindrome")
else:
print("String is Not a palindrome")
To check for palindromes, the above program first takes input from the user (using the input function). Next, determine whether the string has been reversed using the slice operation [start:end: step]. The step value of -1 in this case reverses the string and it will check the condition of whether the string is palindrome or not.
Here is the implementation of the following given code.
This is how we can create a Palindrome program in Python.
Read: Python dictionary append with examples
Python Palindrome program string
- Here we will discuss how to use the string input in the case of a palindrome program.
- Every character in a String was iterated in this Python application using a For Loop. Each character is given an str1 value inside the for loop (before). The palindrome string was then checked using a Python if statement.
Example:
new_str = input("Enter the string value: ")
empty_string = ""
for m in new_str:
empty_string = m + empty_string
print("Reverse Order : ", empty_string)
if(new_str == empty_string):
print("It is a Palindrome String")
else:
print("It is Not a plaindrome string ")
Here is the Screenshot of the following given code
As you can see in the Screenshot we have used the string input value in Palindrome Program.
Read: Check if a list is empty in Python
Python Palindrome program number
- When reversed, a number must remain the same to qualify as a palindrome. It is not a palindrome if the number does not equal the reverse of itself.
- The integer will be converted to a string format and then the string will be reversed using this approach. The final step will involve verifying that the changed number corresponds to the original.
- To convert the integer number to a string we can easily use the str() function. By using string slicing, it will reverse the number.
Example:
new_val=input(("Enter the value:"))
new_reverse = int(str(new_val)[::-1])
if new_val == new_reverse:
print('It is Not Palindrome')
else:
print("It is Palindrome")
In the given example we have used the input statement and then used the str() function to convert the integer value to a string. It will check the condition if the number is reversed then it will return it as a palindrome otherwise it will return “it is not a palindrome’.
Here is the implementation of the following given code.
This is how to create a Palindrome Program by using integer numbers in Python.
Read: Python square a number
Python Palindrome program using loop
- Let us create a palindrome program by using for loop in Python.
- If the reverse number is equal to the same number then the element is called a palindrome number. For example 121=121 So, 121 is a palindrome number.
- we will mention integer numbers while declaring the variables. Then it will check the condition if the number is equal to the reverse number by using the if-else statement.
Example:
new_number = input('Enter the number: ')
n=0
for n in range(len(new_number)):
if new_number[n]!=new_number[-1-n]:
print(new_number,'It is not a Palindrome')
break
else:
print(new_number,'It is a Palindrome')
break
You can refer to the below Screenshot
In this example, we have understood how to create a palindrome program by using for loop in Python.
Read: Python print without newline
Python Palindrome program using recursion
- Simple indexing and a user-defined function are used in conjunction with recursion when it is necessary to determine whether or not a text is a palindrome.
- Palindromes are strings or values that have the same characters in each of their respective indexes when read from right to left and left to right.
- The recursion computes the results of the smaller components of the larger problem and then combines these components to get the larger problem’s solution.
Example:
def check_palindrome(n):
if len(n) < 1:
return True
else:
if n[0] == n[-1]:
return check_palindrome(n[1:-1])
else:
return False
new_variable = input(("Enter a value: "))
if(check_palindrome(new_variable)):
print("This is a palindrome")
else:
print("This is not a palindrome")
In the following given code first, we define the function ‘check_palindrome’ and within this parenthesis, we passed the ‘n’ keyword as an argument. Next, we set the condition if the length of the number is greater than 1 then it will satisfy the condition (n[1:-1]).
Here is the execution of the following given code.
This is how to create a palindrome program by using the recursion method.
Read: 11 Python list methods
longest Palindrome Python program
- Let’s say we have the string S. The longest palindromic substring in S must be located. We are assuming that the string S is 1000 characters long. Therefore, “C” is the longest palindromic substring if the string is “California”.
Example:
Let’s take an example and check how to find the longest palindrome string in Python.
Source Code:
class program(object):
def longestPalindrome(self, t):
new_val = [[False for m in range(len(t))] for m in range(len(t))]
for m in range(len(t)):
new_val[m][m] = True
new_maximum_length = 1
initial = 0
for z in range(2,len(t)+1):
for m in range(len(t)-z+1):
end = m+z
if z==2:
if t[m] == t[end-1]:
new_val[m][end-1]=True
new_maximum_length = z
start = m
else:
if t[m] == t[end-1] and new_val[m+1][end-2]:
new_val[m][end-1]=True
new_maximum_length = z
initial = m
return t[initial:initial+new_maximum_length]
result = program()
print(result.longestPalindrome("California"))
Here is the implementation of the following given code
Read: Create an empty array in Python
Python program for palindrome or not
- A palindrome is a word or a set of numbers made up of letters that spell the same word when reading both forward and backward. Python Palindrome permits punctuation, symbols, letters, and even spaces within the Palindrome words.
- It works by comparing the actual word and the reverse of the word, and if there is an exact match, the matched value is True. Python has three different forms of palindrome methodology: number palindrome, multiple-word palindrome, and single-word palindrome.
- First, we will read the number, and then In a temporary variable, store the letter or number. Next, reverse the number and Compare the temporary variable to a letter or integer that has been reversed.
- Print “This string/number is a palindrome” if the two characters or digits are the same. “This string/number is not a palindrome,” if not, print.
Example:
new_number = 231
rev_number = int(str(new_number)[::-1])
if new_number == rev_number:
print('It is a Palindrome number')
else:
print("It is Not a Palindrome number")
In the following given code first, we will declare the variable and assign the integer number to it. Next, we will use the str() function and which will convert the integer number into the string and assign the reversed number.
Next, we set the condition that the given number is equal to the reverse number or not. If it is equal then it is a palindrome otherwise it will display it is not a palindrome number.
You can refer to the below Screenshot
This is how we can check whether the program is palindrome or not in Python.
Read: Invalid syntax in python
Python program to check if it is palindrome or not
- Here we will discuss whether the string or number is palindrome or not in Python.
- A group of digits called a palindrome number stays the same when read backward. Additionally, it is reversed that these numbers are symmetrical. Its digits are equal to the original number when they are inverted. For instance, the number 121 is a palindrome.
- The first step is to number in reverse order and the second step we will compare with the number before the operation.
Example:
Let’s take an example and check whether the string is palindrome or not in Python.
Source Code:
def Palindrome(t):
return t == t[::-1]
t = "USA"
result = Palindrome(t)
if result:
print("Yes, It is a Palindrome")
else:
print("No, It is not a Palindrome")
In the following given code first, we define the function ‘Palindrome’ function and within this parenthesis, we assigned the variable ‘t’ and set the reverse condition t[::-1]. Next, we will set the condition of the result as palindrome or not.
You can refer to the below Screenshot.
Read: Python Addition Examples
palindrome program in python without using the string function
- To check the palindrome number in Python, we may also use a function. and the string is referred to as a palindrome if its reverse contains the same string.
- In this example, we are not going to use the string function instead of that we will declare a variable and assign the string in which we want to check whether the string is palindrome or not.
- Next, we will create another variable in which the reversed string will be stored and then we used the for-loop method and set the condition if the original number == reversed number. If it is equal then it is a palindrome otherwise it will return it is not a palindrome.
Example:
b="mom"
c=""
for m in b:
c=m+c
if c==b:
print("This word",c,"is palindrome")
else:
print("It",c,"is not a palindrome")
Here is the execution of the following given code
In this example, we have understood how to check the palindrome number in Python without using the string function.
Read: Python invalid literal for int() with base 10
Palindrome program in python using reverse function
- In this example, we will discuss how to create a palindrome program in Python by using the reverse function.
- To perform this task we are going to use the reversed function and Python has a built-in method called reversed that may be used to acquire a sequence’s iterator in reverse.
- The reversed function is similar to the iter() method but with the reversed order. An object used to iterate over an iterable is called an iterator. The iter method on an iterable allows us to create an iterator object.
Example:
new_string_value = 'NewYork'
# This string is reverse.
result = reversed(new_string_value)
if list(new_string_value) == list(result):
print(" String is PALINDROME !")
else:
print(" String is NOT PALINDROME !")
Here is the implementation of the following given code
This is how to create a Palindrome Program in Python by using the reverse function.
Read: Python While Loop Example
Python Program to print palindrome numbers between 1 to 100
- Let us discuss how to print the palindrome numbers between 1 to 100 in Python.
- When a number is reversed and the result is the same as the original, it is said to be a palindrome.
- The user can input the upper limit value using this Python program. The program then produces palindrome numbers from 1 to the user-entered integer. To start, we iterated a loop between 1 and the maximum value using the For Loop.
Example:
lower_val = int(input("Enter the Lowest Number : "))
higher_val = int(input("Enter the Highest Number : "))
print("Palindrome Numbers are between 1 and 100")
for new_number in range(lower_val, higher_val + 1):
new_val = new_number
original_num = 0
while(new_val > 0):
result = new_val % 10
original_num = (original_num * 10) + result
new_val = new_val //10
if(new_number == original_num):
print("%d " %new_number, end = ' ')
In the following given code first, we used the input function and enter the integer values. Next, we iterate the values from 1 to 100.
Here is the implementation of the following given code.
This is how we can print the palindrome numbers between 1 to 100 in Python.
Read: Python check if the variable is an integer
Python Program to find palindrome word
- When reversed, a number must remain the same to qualify as a palindrome. It is not a palindrome if the number does not equal the reverse of itself.
- The integer will be converted to a string format and then the string will be reversed using this approach. The final step will involve verifying that the changed number corresponds to the original.
Example:
new_val=input(("Enter a word:"))
if(new_val==new_val[::-1]):
print("Word is a palindrome")
else:
print("Word is Not a palindrome")
You can refer to the below Screenshot
In this example, we have understood how to display the palindrome word.
Read: Check if a number is a prime Python
palindrome program in python using a while loop
- In this section, we will discuss how we can use the while loop concept to display the palindrome number.
- A code block’s iteration of the while loop in Python runs each time the provided condition, or conditional expression, is true.
Example:
new_num = int(input("Please Enter the number:"))
new_val = 0
i = new_num
while(i > 0):
Result = i % 10
new_val = (new_val * 10) + Result
i = i //10
print("Reverse number is = %d" %new_val)
if(new_num == new_val):
print("%d It is a Palindrome number:" %new_num)
else:
print("%d It is Not a Pallindrome number:" %new_num)
First, we will take an input number from the user and then utilize a while loop to reverse a specified integer. The original and reverse numbers should be compared. The number is a Python palindrome if both numbers exactly matched.
You can refer to the below Screenshot.
As you can see in the Screenshot we have checked whether the number is palindrome or not by using for loop.
Read: Hash table in python
palindrome program in python using if else
- In this section, we will discuss how to check whether it is a palindrome or not by using the if-else condition in Python.
- The reversed string will be located for this procedure, as mentioned before, and then it will be compared to the original string.
Example:
new_str = input("Enter the string value: ")
empty_string = ""
for m in new_str:
empty_string = m + empty_string
print("Reverse Order : ", empty_string)
if(new_str == empty_string):
print("It is a Palindrome String")
else:
print("It is Not a plaindrome string ")
In this example, we have used the input function and set the condition if(new_str == empty_string): it will check if the string is palindrome or not.
Here is the implementation of the following given code.
This is how we can check whether the number is palindrome or not by using the if-else condition.
Read: How to get filename from a path in Python
Palindrome program in python using slicing
- In this example, we will discuss how to use the slicing method for returning the palindrome number.
- To check for palindromes, the above program first takes input from the user (using the input function). Next, determine whether the string has been reversed using the slice operation [start:end: step].
- The step value of -1 in this case reverses the string and it will check the condition of whether the string is palindrome or not.
Example:
new_str=input("Enter the value:")
if(new_str==new_str[::-1]):
print("This is a palindrome number")
else:
print("This is not a palindrome")
Here is the Output of the following given code
Read: Python if else with examples
palindrome program in python using a list
- In this section, we will discuss how to use the list and check whether it is a palindrome or not.
- A method called “check palindrome list” that accepts a string as a parameter is defined. The original string is compared to the inverted string.
- A list is defined outside the method and shown on the console and it is repeated, and the elements are joined together using the “join” technique before being turned into a string and the necessary parameter is passed when calling the method.
Example:
def palindrome(new_val):
if new_val == new_val[::-1]:
print("This list is not a palindrome")
else:
print("This list is a palindrome")
new_list = [121, 'mom', 11, 'rotator', 77]
new_list = ' '.join([str(i) for i in new_list])
palindrome(new_list)
Here is the execution of the following given code
Here is the list of some more related Python tutorials.
- Create a tuple in Python
- Python Program for even or odd
- Python Keywords with examples
- Constructor in Python
- Python Anonymous Function
In this article, we have discussed how to create a palindrome program in python, and also we have checked if it is a palindrome or not also we have covered the below topics.
- Write a Python Palindrome program string
- Write a Python Palindrome program number
- Write a Python Palindrome program using loop
- Write a Python Palindrome program using recursion
- How to write a longest Palindrome Python program
- Python program for palindrome or not
- Write a Python program to check if it is palindrome or not
- How to write a palindrome program in python without using the string function
- Write a palindrome program in python using the reverse function
- Write a Python Program to print palindrome numbers between 1 to 100
- Python Program to find palindrome word
- Write a palindrome program in python using a while loop
- Write a palindrome program in python using if else
- Write a palindrome program in python using slicing
- Write a palindrome program in python using a list
Python is one of the most popular languages in the United States of America. I have been working with Python for a long time and I have expertise in working with various libraries on Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… I have experience in working with various clients in countries like United States, Canada, United Kingdom, Australia, New Zealand, etc. Check out my profile.
Во входном файле записан набор больших латинских букв (не обязательно различных). Разрешается переставлять буквы, а также удалять некоторые буквы. Требуется написать программу, которая из данных букв составит палиндром наибольшей длины, а если таких палиндромов несколько, то можно выводить любой из них.
Написал такой вот код, но он не проходит все тесты:
n = int(input())
str = input()
l = list()
for i in range(len(str)):
l.insert(i, ord(str[i]))
l = sorted(l)
for i in range(len(l)):
l[i] = chr(l[i])
# каждая буква встречается четное количество раз
even = False
one_even = False
e = l[0]
count = 0
for i in range(len(l)):
if l[i] == e:
count += 1
elif count % 2 == 0:
even = True
one_even = True
e = l[i]
count = 1
else:
even = False
break
if count % 2 != 0 and i == (len(l) - 1):
even = False
e = l[0]
count = 0
res_str = ""
if even:
for i in range(len(l)):
if l[i] == e:
count += 1
else:
res_str += e * int((count / 2))
count = 1
e = l[i]
if i == (len(l) - 1):
res_str += e * int((count / 2))
res_str2 = ""
for i in reversed(res_str):
res_str2 += i
print(res_str + res_str2)
# ни одна буква не встречается четное количество раз
elif not one_even:
print(l[0])
# некоторые буквы встречаются нечетное количество раз
else:
s = set(l)
s = list(s)
res_str = ""
odd = ""
count = 0
fiend_Odd = False
for i in range(len(s)):
for j in range(len(l)):
if s[i] == l[j]:
count += 1
if j == (len(l) - 1):
if count % 2 == 0:
res_str += s[i] * int(count / 2)
count = 0
elif not fiend_Odd:
fiend_Odd = True
odd += s[i] * int(count)
count = 0
res_str2 = ""
for i in reversed(res_str):
res_str2 += i
print(res_str + odd + res_str2)
entithat
13.1k2 золотых знака19 серебряных знаков37 бронзовых знаков
задан 9 апр 2021 в 17:46
- Подсчитываем количество каждой из букв в строке
- Для букв, количество которых больше 2, добавляем половину в результат
- Вычитаем из счётчиков букв уже использованное количество
- Добавляем в результирующую строку любую оставшуюся букву со счётчиком 1 (если таких нет, то добавляем пусто)
- и дописываем в конец реверснутую результирующую строку (которая на самом деле была половина палиндрома)
from collections import Counter
letters = "ABCDABCF"
letters_num = Counter(letters)
result = ""
for letter in letters_num:
result += letter * (letters_num[letter] // 2)
letters_num[letter] -= letters_num[letter] // 2 * 2
result += dict(map(reversed, letters_num.items())).get(1,'') + result[::-1]
print(result)
ответ дан 9 апр 2021 в 18:35
GrAndGrAnd
13.4k1 золотой знак8 серебряных знаков23 бронзовых знака
Решил не исправлять ваше решение, а написать своё, если вдруг пригодится. Код выводит ответ в сортированном виде.
Если важно было исправить ваше, то просто мой ответ игнорируйте.
Пробовать код онлайн!
n, s = int(input()), sorted(input())
assert len(s) == n, (n, len(s))
cnt = {}
for c in s:
if c not in cnt:
cnt[c] = 0
cnt[c] += 1
odd = None
for k, v in cnt.items():
if v % 2:
if odd is None:
odd = (k, v)
else:
cnt[k] -= 1
if odd is not None:
del cnt[odd[0]]
cnt = dict(sorted(cnt.items()))
p = (''.join(k * (v // 2) for k, v in cnt.items()) +
(odd[0] * ((odd[1] + 1) // 2) if odd is not None else ''))
p += ''.join(reversed(p[:len(p) - (1, 0)[odd is None]]))
print(p)
Ввод:
8
abcdefab
Вывод:
abcba
Ввод:
4
abab
Вывод:
abba
ответ дан 9 апр 2021 в 18:32
ArtyArty
3,0027 серебряных знаков19 бронзовых знаков
Если коротко:
-
Считаем кол-во букв в даной строке. У нас получится примерно такой массив:
[ 'a1', 'b1', 'c0' ]
. -
Для каждой строки, кол-во повторений какой больше 1 добавляем в результат.
-
И в конце просто дублируем полученную строку и прибавляем ее в конец.
s = 'abbca'
a = sorted(list(set(map(lambda x: f'{x}{s.count(x)}', s))), key=lambda x: -int(x[1:]))
for item in a:
letter, number = item[0], int(item[1:]) // 2
if number >= 1:
o += letter * number
else:
o += letter
break
o += o[:-1][::-1] if int(a[-1][1:]) // 2 == 0 else o[::-1]
print(o) # abcba
P.S. Правда если в палиндром будет состоять из цифр, то надо поправить чуть-чуть.
ответ дан 9 апр 2021 в 18:19
entithatentithat
13.1k2 золотых знака19 серебряных знаков37 бронзовых знаков
def palindrome(letters):
counter = {}
single = ''
result = ''
for ch in letters:
if ch not in counter:
counter[ch] = 1
else:
counter[ch] += 1
if counter[ch] == 2:
counter[ch] = 0
result += ch
for ch, count in counter.items():
if count == 1:
single = ch
break
return result + single + result[::-1]
print(palindrome('aab')) # aba
print(palindrome('qazqaz')) # qazzaq
print(palindrome('abcdef')) # a
ответ дан 9 апр 2021 в 19:00
slippykslippyk
6,1013 золотых знака19 серебряных знаков38 бронзовых знаков
This seems like a fun problem. If you have an industrial-strength test like the Miller Selfridge Rabin test for primality, you can find some real large examples (albeit with a vanishingly small probability of getting a composite):
import random
#The following function finds s and d in
#n-1 = 2^s*d with d odd
def findSD(n):
s = 0
d = n-1
while d % 2 == 0:
s = s + 1
d = d//2
return s,d
def checkBase(a,n):
s,d = findSD(n)
x = pow(a,d,n)
if x == 1 or x == n-1:
return "probable prime"
else:
for i in range(s-1):
x = pow(x,2,n)
if x == 1:
return "composite"
elif x == n-1:
return "probable prime"
#if you get to this stage, -1 not reached despite s-1
#squarings -- so must be composite
return "composite"
def MSR(n,k):
#tests if an odd number is prime
for i in range(k):
a = random.randint(2,n-2)
if checkBase(a,n) == "composite":
return "composite"
#if you get here n has survived k potential witnesses, so
return "probable prime"
def prime(n):
smallPrimes = [2,3,5,7,11,13,17,19]
for p in smallPrimes:
if n == p:
return True
elif n % p == 0:
return False
if MSR(n,20) == "composite":
return False
else:
return True
def randOddPalindrome(n):
digits = [random.choice('13579')]
if n > 1:
m = (n-2)//2
digits.extend(random.choice('0123456789') for i in range(m))
digit = [''] if n%2 == 0 else [random.choice('0123456789')]
digits += (digit + digits[::-1])
return int(''.join(digits))
def findPrimePalindrome(n,trials = 10000):
for i in range(trials):
p = randOddPalindrome(n)
if prime(p): return p
return "No primes found in " + str(trials) + " trials"
for example,
>>> findPrimePalindrome(5)
30803
>>> findPrimePalindrome(6)
'No primes found in 10000 trials'
>>> findPrimePalindrome(101)
10411470210071416936952003803463770311632555360794349706355523611307736430830025963961417001207411401
I briefly suspected a bug when I saw the output for n=6
but then realized that 11 is the only prime palindrome with an even number of digits since all palindromes with an even number of digits are multiples of 11.