简体   繁体   English

带有 python 的回文

[英]Palindromes with python

Trying to use a book to learn python.试图用一本书来学习python。 Here is one of the exercises I'm struggling with.这是我正在努力的练习之一。

3.12 (Palindromes) A palindrome is a number, word or text phrase that reads the same backwards or forwards. 3.12 (Palindromes) 回文是一个数字、单词或文本短语,前后读相同。 For example, each of the following five-digit integers is a palindrome: 12321, 55555, 45554 and 11611. Write a script that reads in a five-digit integer and determines whether it's a palindrome.例如,以下每一个五位整数都是回文数:12321、55555、45554 和 11611。编写一个脚本,读取五位数字 integer 并确定它是否是回文数。 [Hint: Use the // and % operators to separate the number into its digits.] [提示:使用 // 和 % 运算符将数字分隔为数字。]

Any help is appreciated.任何帮助表示赞赏。

Program Explanation节目说明

  1. User must first enter the value of the integer and store it in a variable.用户必须首先输入 integer 的值并将其存储在变量中。
  2. The value of the integer is then stored in another temporary variable.然后将 integer 的值存储在另一个临时变量中。
  3. The while loop is used and the last digit of the number is obtained by using the modulus operator.使用 while 循环,并使用取模运算符获得数字的最后一位。
  4. The last digit is then stored at the one's place, second last at the ten's place and so on.然后将最后一个数字存储在个位,倒数第二个存储在十位,依此类推。
  5. The last digit is then removed by truly dividing the number with 10.然后通过将数字真正除以 10 来删除最后一位数字。
  6. This loop terminates when the value of the number is 0.当数字的值为 0 时,此循环终止。
  7. The reverse of the number is then compared with the integer value stored in the temporary variable.然后将该数字的倒数与存储在临时变量中的 integer 值进行比较。
  8. If both are equal, the number is a palindrome.如果两者相等,则该数是回文数。
  9. If both aren't equal, the number isn't a palindrome.如果两者不相等,则该数字不是回文。
  10. The final result is then printed.然后打印最终结果。
n=int(input("Enter number:"))
temp=n
rev=0
while(n>0):
    dig=n%10
    rev=rev*10+dig
    n=n//10
if(temp==rev):
    print("The number is a palindrome!")
else:
    print("The number isn't a palindrome!")

I don't know answering a question will go against the code of conduct of not.我不知道回答问题会不会违反行为准则。 But here we go.但在这里我们 go。

If the integer is always five digits then you can do it like followings:如果 integer 始终是五位数字,那么您可以这样做:

def check_palindrome(number):
    number = str(number) # Will make the number string

    if number[0]==number[-1] and number[1]==number[-2]:
        return True
    else:
        return False

print(check_palindrome(12321))
print(check_palindrome(55555))
print(check_palindrome(12345))

Answer:回答:

True
True
False

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM