首页 > 编程知识 正文

Python 语言中的回文程序

时间:2023-11-25 15:30:10 阅读:309187 作者:JAJC

什么是回文?

回文是即使数字和字母颠倒了也保持不变的数字或字母。

例如:

121,11,414,1221,74747 是回文数字。

妈妈,爸爸,女士,参考是回文字母。

JAVATPOINT、PROGRAM、JAVA 不是回文字母。

回文算法

  • 读数字或字母。
  • 将字母或数字保存在临时变量中。
  • 颠倒字母或数字。
  • 将临时变量与颠倒的字母或数字进行比较。
  • 如果两个字母或数字相同,打印“这个字符串/数字是回文。”
  • 否则打印,“这个字符串/数字不是回文。”

回文程序

程序 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 !

程序二:回文串程序


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!

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。