简体   繁体   中英

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

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? True'

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

output -> 'num_x palindrome? 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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