Home > Backend Development > Python Tutorial > How to write a function in python to determine the number of palindromes?

How to write a function in python to determine the number of palindromes?

coldplay.xixi
Release: 2020-06-23 11:57:22
Original
12384 people have browsed it

How to write a function in python to determine the number of palindromes?

#How to write a function in python to determine the number of palindromes?

How to write a function in python to determine the palindrome number:

Let n be an arbitrary natural number. If the natural number n1 obtained by rearranging the digits of n is equal to n, then n is called a palindrome number. For example, if n=1234321, then n is called a palindrome number; but if n=1234567, then n is not a palindrome number.

The above explanation means that the palindrome number and the result after reverse order are equal. This is the criterion for judging whether a value is a palindrome.

The code is also implemented based on this idea.

# -*- coding: utf-8 -*-
"""
Created on Sun Aug  5 09:01:38 2018
@author: FanXiaoLei
"""
#判断回文数
def hw(n):
    p=n
    k=0
    while p!=0:
        k=k*10+p%10
        p=p//10
    if k==n:
        return True
    else:
        return False
print(hw(121))
print(hw(13451))
Copy after login

The results are as follows:

How to write a function in python to determine the number of palindromes?

Of course we can use the reversed function in python to reverse the order. This will be much simpler. The code is as follows:

# -*- coding: utf-8 -*-
"""
Created on Mon Aug  6 07:03:59 2018
@author: FanXiaoLei
"""
def hw(n):
    p=str(n)
    k=''.join(reversed(p))
    if k== p:
        return True
    else:
        return False
print(hw(121))
print(hw(1234531))
Copy after login

The result is as shown:

How to write a function in python to determine the number of palindromes?

Recommended tutorial: "python video tutorial"

The above is the detailed content of How to write a function in python to determine the number of palindromes?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template