Как найти число палиндром питон

Описание задачи

Программа принимает на вход число и определяет, является ли оно палиндромом.

Решение задачи

  1. Принимаем число и записываем его значение в переменную.
  2. Создаем еще одну переменную и помещаем в нее то же самое значение.
  3. Далее при помощи цикла while мы «переворачиваем» исходное число, то есть находим как оно пишется в обратном порядке. Мы уже решали такую задачу ранее.
  4. Далее сравниваем полученное число с сохраненной ранее копией первоначального числа. Если они равны, то исходное число — это палиндром.
  5. Выводим полученный результат на экран.
  6. Конец.

Исходный код

Ниже дан исходный код для проверки, является ли введенное число палиндромом. Результаты работы программы также даны ниже.

n = int(input("Введите число:"))
temp = n
rev = 0
while(n > 0):
    dig = n % 10
    rev = rev * 10 + dig
    n = n // 10
if(temp == rev):
    print("Это палиндром!")
else:
    print("Это не палиндром!")

Объяснение работы программы

  1. Пользователь вводит число и оно записывается в переменную n.
  2. Затем это же число дублируется в переменную temp.
  3. Далее при помощи уже разобранной нами процедуры число n записывается в обратном порядке и сохраняется в переменной rev.
  4. Затем это число (находящееся в переменной rev) сравнивается с сохраненной нами ранее копией введенного числа (которая находится в переменной temp).
  5. Если эти числа равны, то исходное число является палиндромом.
  6. В противном случае оно палиндромом не является.
  7. В завершении мы выводим конечный результат на экран.

Результаты работы программы

Пример 1
Введите число:121
Это палиндром!
 
Пример 2
Введите число:567
Это не палиндром!

Примечание переводчика

Как и в прошлом примере, при помощи методов строк эту задачу можно решить гораздо короче. Предоставим читателям самим это сделать.

Hi I’m working on a python function isPalindrome(x) for integers of three digits that returns True if the hundreds digit equals the ones digit and false otherwise. I know that I have to use strings here and this is what I have:

def isPal(x):
    if str(1) == str(3):
        return "True"

    else:
        return "False"

the str(0) is the units place and str(2) is the hundreds place. All I’m getting is False? Thanks!

ConcurrentHashMap's user avatar

asked Jul 31, 2012 at 13:38

George Putin's user avatar

9

Array access is done with [], not (). Also if you are looking for hundreds and units, remember that arrays are 0 indexed, here is a shortened version of the code.

def is_pal(num):
    return num[0] == num[2]

>>> is_pal('123')
False
>>> is_pal('323')
True

You might want to take in the number as a parameter and then convert it to a string:

def is_pal(num):
    x = str(num)
    return x[0] == x[2]

Note that you can simply just check if string is equal to it’s reverse which works for any number of digits:

>>> x = '12321'
>>> x == x[::-1]
True

answered Jul 31, 2012 at 13:40

jamylak's user avatar

jamylakjamylak

128k30 gold badges230 silver badges230 bronze badges

4

str(1) will create a string of the integer value 1. Which won’t equal the string value of the integer value 3 – so it’s always False.

You should return True and False, rather than strings of “True” and “False”…

This is what you’re aiming for taking into account the above… (which works with any length)

def pal(num):
    forward = str(num)
    backward = ''.join(reversed(forward))
    return forward == backward

answered Jul 31, 2012 at 13:42

Jon Clements's user avatar

Jon ClementsJon Clements

138k32 gold badges244 silver badges278 bronze badges

Your problem is that str(1) == '1' and str(3) == '3'. You’re also returning string values reading 'True' and 'False' instead of using the actual True and False values.

Let me propose a much simpler function for you:

def isPal(x):
    s = str(x)          # convert int to str
    return s == s[::-1] # return True if s is equal to its reverse

s[::-1] creates a reverse of the string; e.g. 'foo'[::-1] == 'oof'. This works because of extended slice notation.

glglgl's user avatar

glglgl

88.5k13 gold badges148 silver badges217 bronze badges

answered Jul 31, 2012 at 13:44

zigg's user avatar

ziggzigg

20.2k7 gold badges36 silver badges54 bronze badges

Not sure why people are sticking to the string idea when division and modulo will do:

def isPal(x):
    return (x/100)%10 == x%10

if the number is no larger than 999 (3 digits as the OP stated) then it simplifies to

def isPal(x):
    return x/100 == x%10

answered Jul 31, 2012 at 13:48

jmetz's user avatar

jmetzjmetz

12k3 gold badges30 silver badges41 bronze badges

7

str() casts a value into a str. You want to access each character. You might want to benchmark a few different techniques.

>>> t1 = timeit.Timer(stmt="""
... def isPal(x):
...     return x//100 == x%10
... isPal(434)
... isPal(438)
... """)
>>> t2 = timeit.Timer(stmt="""
... def isPal(x):
...     return str(x)[0] == str(x)[2]
... isPal(434)
... isPal(438)
... """)
>>> print "%.2f usec/pass" % (1000000 * t1.timeit(number=100000)/100000)
0.97 usec/pass
>>> print "%.2f usec/pass" % (1000000 * t2.timeit(number=100000)/100000)
2.04 usec/pass

So, it looks like the mod technique works:

def isPal(x):
    return x//100 == x%10

answered Jul 31, 2012 at 13:44

aaronlevin's user avatar

aaronlevinaaronlevin

1,4332 gold badges13 silver badges18 bronze badges

4

str(1) just gives you the string representation of the number 1:

>>> x = 357
>>> str(1)
'1'

What you want is the first index of the string representation of x.

>>> x = 357
>>> str(x)    #string representation of x
'357'
>>> str(x)[0] #first index of that
'3'
>>> str(x)[2] #third index of that
'7'
>>> str(x)[0]==str(x)[2] #compare 1st and last
False
>>> x = 525
>>> str(x)[0]==str(x)[2] #compare 1st and last
True

answered Jul 31, 2012 at 13:41

Claudiu's user avatar

ClaudiuClaudiu

223k164 gold badges479 silver badges679 bronze badges

you compare number 1 and 3, but you needt to compare index of input variable.

x = 1000
def isPal(x):
    return str(x[-1]) == str(x[-3]):

answered Jul 31, 2012 at 13:41

yedpodtrzitko's user avatar

yedpodtrzitkoyedpodtrzitko

8,8912 gold badges39 silver badges40 bronze badges

It looks like you still need to study Python syntax

Here is a way to achieve what you need :

>>> def isPal(x):
...     x_as_str = str(x)
...     if len(x_as_str) != 3:
...         raise Exception("{} is not of length 3".format(x))
...     return x_as_str[0] == x_as_str[2]
...
>>> isPal(42)
Traceback (most recent call last):
  File "<input>", line 1, in <module>
  File "<input>", line 4, in isPal
Exception: 42 is not of length 3
>>> isPal(420)
False
>>> isPal(424)
True

answered Jul 31, 2012 at 13:43

Alexis Huet's user avatar

Alexis HuetAlexis Huet

7554 silver badges11 bronze badges

str(x) delivers the string value of whatever you pass to it, so in your case the string "1" or the string "3". But what you actually want is to access the 1st and 3rd digit of the given number. So, first you want to convert that number to string (e.g. with str(num)), and then you have to consider that indices in strings begin with 0, not with 1.
So working code culd e.g. look like this:

def isPal(x):
  if str(x)[0] == str(x)[2]:
    return 'true'
  else:
    return 'false'

Output:

> isPal(101)
true
> isPal (203)
false

answered Jul 31, 2012 at 13:40

codeling's user avatar

codelingcodeling

11k4 gold badges41 silver badges69 bronze badges

A smaller solution for this would be:

def isPalindrome(x):    
    return str(x) == str(x)[::-1]

This will work for words and integer values.

answered Jun 6, 2016 at 11:28

Mithun B's user avatar

def is_palindrome() :
a=(raw_input("enter the name : "))
b=a[::-1]
    if b == a:
    print " it is palindarome"
    else:
    print "  it is not palindarome"

is_palindrome()

answered Jul 30, 2014 at 12:00

user3886969's user avatar

1

What is a Palindrome?

A palindrome is a word, number, or any string of characters which reads the same backward as it reads forward.

You may have to check whether a number is a palindrome or not in everyday programming and competitive programming. It is straightforward to reverse a number and check it. However, you need to perform the one-liner logic to check readability and reduce the lines of code. From the following examples, you can understand what a palindrome number in python is.

Few examples: detartrated, 1567651, 02/02/2020, Malayalam

So this article shows you various ways you can write a program to check whether a given input is a palindrome or not, using Python.

Method 1:

The most naïve solution which comes to mind is to reverse the number and check if it equals the input number. It can be done as follows:

number = int(input()); 

reverse = 0

while number > 0: 

    digit = number % 10

    reverse = reverse * 10 + digit 

    number = number // 10

if number==reverse:

    print(“it is a palindrome!”)

else:

    print(“it is not a palindrome!”)

However, this compromises the readability of the code and has more lines of code than required. Checkout our online data science course to learn more.  

Here’s a short and sweet way to check a number using just one line.

Method 2:

The trick is to take the input number as a str data type instead of int. Then you can use the [::-1] slicing technique to obtain the reverse of a string and check for equality in the if statement itself.

A slicing method helps you determine the reverse. You can also use the built-in ‘’.join(reversed()). There are several other ways to reverse a string, but the following section discusses a simple palindrome number program in python.

This program compares the reversed string with the original string. It returns “True” if both the strings are equal, else it returns “False”.

number = input() 

if number == number[::-1]: 

    print(“it is a palindrome!”) 

else: 

    print(“it is not a palindrome!”) 

Method 3:

This is a recursive method to check if an array is a palindrome or not.

def isPalindrome(numbers, start, end): 

    if start >= end: 

        return True

      if numbers[start] == numbers[end]: 

        return isPalindrome(numbers, start + 1, end – 1) 

    else: 

        return False

numbers= list(map(int, input().split()))

n=len(numbers)

if isPalindrome(numbers, 0, n-1):

    print(“it is a palindrome!”) 

else: 

    print(“it is not a palindrome!”) 

The isPalindrome function checks whether the first and last array elements are same or not. If not, the function immediately returns False. Otherwise it recursively checks for the next extreme elements till the two pointers meet in the middle.

Read: Python Project Ideas & Topics

How does Palindrome work in Python?

The function’s argument is considered and its reverse is determined. This is then stored in a separate variable. The length technique helps determine the reverse.

This step determines the variable’s length, and a manual reverse is employed on top of the length.

The actual variable and variable with reverse stored are compared to determine whether they contain the same value. palindrome number in python

The “True” value is returned from the function if both values are matched. The “False” value is returned from the function if both the values don’t match.

The message “The string is a palindrome” is printed when the value is “True”. The message “The string is not a palindrome” is printed when the value is “False”.

Methods to find Palindrome in Python:

1) Without determining the reverse of the string:

It constantly compares the characters present at the first and last index of the string. The comparison continues until they are unequal.

The following section discusses this method with the help of two examples.

Example-1:

String value “malayalam”:

It compares the first and last characters and they are equal. It then compares the second and second last characters and they are equal. The process in this palindrome number program in python continues until all characters are checked this way. Hence, the string is a palindrome.

Example-2:

String value “shops”:

Only the first and last characters are equal. When the second and second last characters are compared, they are found unequal. So, it is not a palindrome.

You can implement this idea through two pointers or recursion. Let’s first implement using pointers. You begin with the start pointer 0 and the end pointer at the last index. The comparison goes on and if characters are equal, the start pointer is incremented and the end pointer is decremented.

The question that arises in this palindrome number python is when to return False. There is no need to look for subsequent indexes, so “False” is returned if the characters for any set of pointers are unequal.

When to return “True” in the palindrome number program in python? If a string is a Palindrome, “True” is returned when both the pointers are equal, or the start pointer surpasses the end pointer and returns true.

For Loop to check for Palindrome in Python:

You can use the “For” loop in Python to loop over a string in reverse order. Let’s check how to use the “For” loop to check for the palindrome number program in python.

s = ‘Poor Dan is in a droop’

def palindrome(s):

s = s.lower().replace(‘ ‘, ”)

reversed_string = ”

for i in range(len(s), 0, -1):

     reversed_string += s[i-1]

return a_string == reversed_string 

print(palindrome(s))

# Returns: True

The output of the above program shows that the entered string is Palindrome.

checkPalindrome() method to check for Palindrome in Python:

The checkPalindrome()is a user-defined method that accepts a value and returns a value if the reciprocal equals the element itself. So, we accepted the number provided by the user as a parameter to the checkPalindrome()method. The return variable is therefore initialized with the variable “chck”. When comparing the values ​​of the variable “chck”, if it contains 1, it means the given value is a palindrome. Otherwise, the entered value is not a palindrome.

For example, if the entered number is “987569”. After reversing the number, it is compared to the originally entered number. But they both are not equal. So, “987569” is not a palindrome number.

reversed() method to check for Palindrome in Python:

The reversed() function in Python determines whether the entered value or string is a palindrome or not. It accepts a series of characters and returns the inverse iterator. Instead of the list catalog [::-1], reversed() method is used to inverse the series of values within the string.  The real and inverted string is compared elements by elements. Finally, it determines whether the number is palindrome or not.

Code for the reversed() method to check for palindrome number python:

w = input()

if str(w) = = “” . join (reversed(w))

print (“It is a palindrome”)

else

print (“It is not a palindrome) 

For example, you can use the reversed() method to check if the string “nayan” is a palindrome or not. Firstly, the “.join (reversed () function” helps to analyze the inverse of the real string. The “==” equation operator is used to compare both the real string and the inverse string. The message “It is a palindrome” is printed if the real string and the reverse string are equal.

The fastest way to check if a string is Palindrome or not in Python:

The fastest way to check for a palindrome number python is string indexing. It can work up to 70 times faster than a “For” loop.

Top Data Science Skills to Learn

Common coding interview questions related to palindromes

#1 Longest palindromic Substring

Given only one string as an input, you have to return the length of the longest palindromic substring in the string.

Eg:

Input: ‘acbcbabcc’

Output: 5  (‘cbabc’)

Approach:

If we try to relate this to one of the most common problems of DP, the longest common substring, here the difference is that we are given only one input string whereas LCS uses two strings. Since we know a palindrome is exactly equal to its reverse, we can make the second string as the reverse of our given input.

Now this becomes exactly the same as finding LCS.

def LCSubstr(A, B, m, n):  

    LCSub = [[0 for i in range(n+1)] for j in range(m+1)] 

    ans = 0

         for i in range(m+1): 

        for j in range(n+1): 

            if (i == 0 or j == 0): 

                LCSub[i][j] = 0

            elif A[i-1] == B[j-1]: 

                LCSub[i][j] = 1 + LCSub[i-1][j-1]

                ans = max(ans, LCSub[i][j]) 

            else: 

                LCSub[i][j] = 0

    return ans 

str1 = input()

str2 = str1[::-1]

 m = len(str1) 

n = len(str2) 

print(‘Length of longest palindromic substring = ‘, LCSubstring(str1, str2, m, n)) 

So for the above input, we obtain the two strings as

‘acbcbabcc’ and

‘ccbabcbca’

The longest common substring becomes ‘cbabc’ which is of length 5.

Read our popular Data Science Articles

#2 Check if an Anagram of a String is a Palindrome

Given a string as an input, you have to check if any anagram of the string can be a palindrome or not and return yes/no accordingly.

Eg:

Input: ‘pythonpython’

Output: Yes

(while the string itself is not a palindrome, a possible anagram ‘pythonnohtyp’ does form a palindrome)

Input: ‘harrypotter’

Output: No

Approach:

If you notice carefully, whenever we have a palindrome string of even length, all the characters in the first half are repeated in the second half. This means all characters present in the string occur an even number of times.

When the length is odd, all characters to the left of the middle element (not inclusive) occur the same number of times in the right side of the middle element. This means there is only one character which occurs an odd number of times (middle element) and all the others occur even number of times.

upGrad’s Exclusive Data Science Webinar for you –

ODE Thought Leadership Presentation

Using this logic, we can store the count of the characters in the string in a hash and check for these constraints to get the required answer.

CHAR_RANGE = 256

str1 = input()

freq = [0 for i in range(CHAR_RANGE)]  

for i in str1: 

    freq[ord(i)] += 1  #ord(x) gives the unicode value of x  

num_odds = 0

for i in range(CHAR_RANGE): 

    if freq[i] & 1: 

        num_odds += 1

       if (num_odds > 1): 

        print(“Yes”)

    else:

     print(“No”) 

Our learners also read: Top Python Courses for Free

Top Data Science Skills to Learn

Conclusion

In conclusion, the palindrome problems are very common and interesting. They are useful to solve various mathematical puzzles and competitive programming questions.

If you are curious to learn about data science, check out IIIT-B & upGrad’s Executive PG Programme in Data Science which is created for working professionals and offers 10+ case studies & projects, practical hands-on workshops, mentorship with industry experts, 1-on-1 with industry mentors, 400+ hours of learning and job assistance with top firms.

What is the time complexity of the Palindrome program?

The number of elementary operations done by the method is often used to estimate time complexity, assuming that each elementary process takes a set amount of time to complete. The time complexity of determining whether or not a number is a palindrome is O(log10 (n)). When we check for the values to be a palindrome, we divide the number or value by ten in each iteration. As a result, the temporal complexity is equal to the number of digits in a number.

How is / different from // operator in Python?

When we use the divide operator, i.e., a single slash (/) in Python, the compiler simply divides the two values on the right and left sides of the slash. But when we use double slash(//), i.e., floor division, we ask the compiler to carry out the typical division process, but the result it yields is the biggest integer possible close to the answer. This integer is either less than or equal to the result of normal division.

What is the entry-level salary of a Python Developer?

It’s a well-known fact that Python is widely used in most industries and companies, making Python the second-highest-paid computing language. Python is also the favorite programming language amongst students and professionals because it is easy to learn and is highly flexible. The entry-level salary of a Python Developer in India is around INR 4,27,293 per annum on average. Professionals learning Python have a lot of scope as Python is also used in other fields such as Data Science and Machine Learning.

Want to share this article?

Prepare for a Career of the Future

Be a Certified Data Scientist – Advanced Certificate Programme in Data Science

Learn More

Палиндром в 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 вместе с вами, читаю, собираю и записываю информацию опытных программистов.

Sometimes, we have an application of checking a number is palindrome or not and it’s quite common while day-day programming or competitive programming, it’s easy to reverse a number and check it but sometimes for readability and reducing lines of code, we require to perform this in one-liner logic. Let’s discuss certain ways in which this can be achieved.

Input : test_number = 12321 Output : True Input : test_number = 1234 Output : False

Method #1 : Using math.log() + recursion + list comprehension The combination of above three functions can perform this particular task easily, the logs function extracts the number of digits which is powered by 10 to get the number for that iteration for comparison. The process is recurred to test for palindrome. 

Python3

import math

def rev(num):

    return int(num != 0) and ((num % 10) *

             (10**int(math.log(num, 10))) +

                          rev(num // 10))

test_number = 9669669

print ("The original number is : " + str(test_number))

res = test_number == rev(test_number)

print ("Is the number palindrome ? : " + str(res))

Output:

The original number is : 9669669
Is the number palindrome ? : True

Time Complexity: O(n)
Auxiliary Space: O(n)

  Method #2 : Using str() + string slicing This can also be done by converting the number into a string and then reversing it using the string slicing method and comparing it, truth of which returns the answer to it. 

Python3

test_number = 9669669

print ("The original number is : " + str(test_number))

res = str(test_number) == str(test_number)[::-1]

print ("Is the number palindrome ? : " + str(res))

Output:

The original number is : 9669669
Is the number palindrome ? : True

Time Complexity: O(n)
Auxiliary Space: O(1)

We can also read input as string and then simply check for palindrome. 

Python3

num = input("Enter a number")

if num == num[::-1]:

    print("Yes its a palindrome")

else:

    print("No, its not a palindrome")

  Method #3 : Using all() and zip()

Python3

print(all(a == b for a, b in zip(str(12321), reversed(str(12321))))) 

print(all(a == b for a, b in zip(str(1234), reversed(str(1234))))) 

This code uses the all function and a generator expression to check if a number is a palindrome.

The zip function takes two iterables (in this case, the string representation of the number and the reversed string representation of the number) and returns an iterator of tuples, where each tuple contains one element from each iterable. For example, zip(str(12321), reversed(str(12321))) would return an iterator of the following tuples:

(‘1’, ‘1’)
(‘2’, ‘2’)
(‘3’, ‘3’)
(‘2’, ‘2’)
(‘1’, ‘1’)

The generator expression (a == b for a, b in zip(str(12321), reversed(str(12321)))) generates a generator that returns True if the elements a and b are equal, and False otherwise. In this case, it would generate the following values:

True
True
True
True
True

The all function returns True if all of the elements in the generator are True, and False otherwise. In this case, it would return True because all of the elements in the generator are True.

Time complexity: O(n), where n is the length of the number. This is because the zip function and the generator expression both have a time complexity of O(n).

Space complexity: O(1), because the code only uses a fixed amount of space regardless of the length of the number.

Last Updated :
24 Mar, 2023

Like Article

Save Article

Добавить комментарий