#Exercise 9: Check Palindrome Number
#Numbers stored in x/y
x = 121
y = 125
#Transferred int in list
num_y = list(str(y))
num_x = list(str(x))
#Flipping the list
rev_y = num_y[::-1]
rev_x = num_x[::-1]
#Compare the flip if they are palindrome
if num_y == rev_y:
print("Yes. given number is palindrome number")
else:
print("No. given number is not palindrome number")
if num_x == rev_x:
print("Yes. given number is palindrome number")
else:
print("No. given number is not palindrome number")
使用def
定义函数
不需要将整型参数从字符串转换为列表。只需对字符串进行操作-它支持切片反转字符串。
根据字符串是否与反向字符串相同,从函数返回True
或False
。
def is_palindrome(n):
s = str(n)
return s == s[::-1]
x = 121
print(is_palindrome(x))
# True
y = 125
print(is_palindrome(y))
# False
这是排序方法:
num = '1421'
if num == str(num)[::-1]:
print('The given number is PALINDROME')
else:
print('The given number is NOT a palindrome')
输出:
The given number is NOT a palindrome
这对你有帮助。
你应该使用函数。
def print_if_number_is_palindrom(number):
if str(number) == str(number)[::-1]:
print("Yes, given number is palindrome number")
else:
print("No, given number is not palindrome number")
x = 121
y = 125
print_if_number_is_palindrom(x)
print_if_number_is_palindrom(y)
目标:
- 清理代码
- 将主逻辑移动到函数
方法:
- 创建通用函数,可用于任何类型的回文
- 将数字作为字符串传入函数
def is_palindrome(term):
for i in range(len(term)):
if term[i] != term[(len(term)-i-1)]:
return False
return True
num_x = str(121)
print('num_x palendrome?',is_palindrome(num_x))
def is_palindrome(term):
for i in range(len(term)):
if term[i] != term[(len(term)-i-1)]:
return False
return True
num_x = str(121)
print('num_x palendrome?',is_palindrome(num_x))
输出→"num_x回文呢?真正的'
num_y = str(122)
print('num_y palendrome?',is_palindrome(num_y))
输出→"num_x回文呢?假'
注意:
从技术上讲,方法是在类中定义的函数。因此,您实际要求的是:
class ClassExample():
def __init__(self):
self.string = ''
def is_palindrome(self,term):
for i in range(len(term)):
if term[i] != term[(len(term)-i-1)]:
return False
return True
ex = ClassExample()
测试:
ex.is_palindrome('121')