Home>Article>Backend Development> python palindrome number judgment

python palindrome number judgment

silencement
silencement Original
2019-06-05 11:20:01 35216browse

python palindrome number judgment

What is a palindrome number?

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

Enter a 5-digit number and use python to 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.

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)

Method 2: Define 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))

User input 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)

To determine whether any integer is a palindrome number:

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

For more Python-related technical articles, please visit thePython Tutorialcolumn to learn!

The above is the detailed content of python palindrome number judgment. 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