Home >Backend Development >Python Tutorial >How to determine whether a palindrome number is in python

How to determine whether a palindrome number is in python

爱喝马黛茶的安东尼
爱喝马黛茶的安东尼Original
2019-08-02 14:27:3921369browse

How to determine whether a palindrome number is in python

What is a palindrome number:

There is a type of number that is the same number when viewed backwards and forwards, for example : 12321, 1221, 2332, etc. Such numbers are called: palindrome numbers.

Example: Enter a 5-digit number and determine whether it is a palindrome number. That is, 12321 is a palindrome number, the ones digit is the same as the thousands digit, and the tens digit is the same as the thousands digit. Find all the palindromes in the 5-digit number:

Method 1. Use for loop

# 找出5位数中所有的回文数:
for i in range(10000,100000):   # 遍历所有的5位数
    s = str(i)    # 将数字转换成字符串类型,即可以用索引取出每一位上的数字
    if s[0] == s[-1] and s[1] == s[-2]:   # 字符串的索引
        print(i)

Related recommendations: "Python Video Tutorial

Method 2. Define the function

def is_huiwen(n):
    reversed_str= str(n)
    return reversed_str == reversed_str[-1::-1]   # 
output = filter(is_huiwen,range(10000,100000))
print(list(output))

·The user inputs a 5-digit number to determine whether it is a palindrome number:

# 输入一个5位数,判断它是否是回文数:
a = int(input(" 请输入一个5位整数:"))
s = str(a)
if s[0] == s[-1] and s[1] == s[-2]:
    print(" %d 是一个回文数!" % a)
else:
    print(" %d 不是一个回文数!" % a)

· Determine whether any integer is a palindrome number:

n = int(input('请输入一个整数:'))
s = str(n)
f = True
for i in range(len(s)//2):
    if s[i] != s[-1-i]:
        f = False
        break
if f:
    print('%d 是一个回文数' % n)
else:
    print('%d 不是一个回文数' % n)

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

Statement:
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