简体   繁体   English

如何使用方法 Python 缩短此代码

[英]How can i make this code shorter with a methond Python

#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")

Define a function using def .使用def定义一个函数
No need to change the integer argument converted to string into a list.无需将转换为字符串的整数参数更改为列表。 Just operate with the string - it supports slicing to reverse the string.只需对字符串进行操作 - 它支持切片以反转字符串。
Return True or False from the function depending on whether the string is the same as the reverse string.根据字符串是否与反向字符串相同,从函数返回TrueFalse

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

You should use a function.你应该使用一个函数。

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)

The Goal:目标:

  • Clean up code清理代码
  • Move the main logic to a function将主要逻辑移至函数

Approach:方法:

  • Create generalized function which can be used for any type of palindrome创建可用于任何类型回文的广义函数
  • Pass numbers into function as string将数字作为字符串传递给函数

Result结果

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

output -> 'num_x palindrome?输出 -> 'num_x 回文数? True'真的'

num_y = str(122)
print('num_y palendrome?',is_palindrome(num_y))

output -> 'num_x palindrome?输出 -> 'num_x 回文数? False'错误的'

Note:笔记:

Technically a method is a function defined within a class .从技术上讲,方法是在类中定义的函数 As such what you are actually asking for is this:因此,您实际要求的是:

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()

Test:测试:

ex.is_palindrome('121')

here is Sorter method:这是排序器方法:

num = '1421'
if num == str(num)[::-1]:
    print('The given number is PALINDROME')
else:
    print('The given number is NOT a palindrome')

output:输出:

The given number is NOT a palindrome

This will help you.这将对您有所帮助。

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

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