Pthon Title: Judging whether the data is palindromes

Posted by soulzllc on Mon, 30 Sep 2019 11:16:00 +0200

Introduction:

The popular point of palindromes is that the order of numbers read along and backward is the same.

Reflection:

One can think of the first way is to compare one by one, and then carefully find that only half of the comparison is possible. Here are two methods, one is to compare one by one, the other is to compare half (if the number of data is singular, then to [n/2], even is n/2).

Method 1:

# O(n), instability (worst case and best case)
@count_time
def test(num):
    num = str(num)
    num_len = len(num)
    for i in range(num_len):
        if num[i] != num[num_len - i - 1]:
            return 'Not palindromes!'
        if i == num_len - 1:
            return 'It's palindrome!'

Method two:

# O(n/2), instability (worst case and best case)
@count_time
def two_test(num):
    num = str(num)
    num_len = len(num)
    iden = num_len // 2
    for i in range(iden):
        if num[i] != num[num_len - i -1]:
            return 'Not palindromes!'
        if i == iden - 1:
            return 'It's palindrome!'

Comparison:

A time-consuming decorator for writing a test function:

from functools import wraps
def count_time(func):
    @wraps(func)
    def wrapper(*args, **kwargs):
        start_time = default_timer()
        result = func(*args, **kwargs)
        end_time = default_timer()
        total_time = end_time - start_time
        return result, total_time
    return wrapper

Add @count_time to two functions, using the following test time

spend_test1 = test(2332)
spend_two_test1 = two_test(2332)
print(spend_test1)
print(spend_two_test1)
spend_test2 = test(23789016890421578970124789037681643074247034618673098742107987512409861098732)
spend_two_test2 = two_test(23789016890421578970124789037681643074247034618673098742107987512409861098732)
print(spend_test2)
print(spend_two_test2)

The above code results:

('It's palindrome!', 4.5000000000045e-06)
('It's palindrome!', 1.8999999999991246e-06)
('It's palindrome!', 1.1099999999999999e-05)
('It's palindrome!', 5.299999999999749e-06)

Summary: The time complexity of method 1 is O(n), instability (worst case and best case), method 2 is O(n/2), instability (worst case and best case). In the case of large data sets, the time efficiency of method 2 is much higher than that of method 1.