Special palindrome number for Lanqiao Cup basic exercises (implemented in python)

Resource limit
Time limit: 1.0s Memory limit: 512.0MB

Problem description
123321 is a very special number, it reads from the left and reads from the right is the same.
Enter a positive integer n, and program to find all such five-digit and six-digit decimal numbers so that the sum of each digit is equal to n.

Input format
Input one line, including a positive integer n.
  
Output format
according to the order from small to large outputs an integer satisfying the condition, each integer per line.
  
Sample input
52

Sample output
899998
989989
998899

Data scale and convention
1<=n<=54


Code submitted for the first time:

# 遍历所有五位数和六位数,
# 求各位数字之和判断是否等于n,
# 接着将数字转成字符串再逆转然后判断是否为回文数
n = int(input())
for i in range(10000,1000000) :
    num = str(i)
    result = 0
    for j in num :
        result += int(j)
    if result == n and num == num[::-1] :
        print(num)

Result: severe timeout! The analysis found that there are two loops in the middle, and the summation is also a loop, and for the numbers that are not "special palindrome numbers", the summing operation is also performed, and many invalid operations are done.


Code submitted for the second time:

# 先判断是回文数,再求和
n = int(input())
for i in range(10000,1000000) :
    num = str(i)
    if num == num[::-1] :
        result = 0
        for j in num :
            result += int(j)
        if result == n :
            print(num)

The result: full marks! But it took 390ms


The third code submitted:

n = int(input())
my_list = []
for i in range(100,1000) :
	# 如果该数字是6位数
    if sum(map(int,str(i) + str(i)[::-1])) == n :
        my_list.append(str(i) + str(i)[::-1])
        
    # 如果该数字是5位数
    if sum(map(int,str(i) + str(i)[:2][::-1])) == n :
        my_list.append(str(i) + str(i)[:2][::-1])
for i in sorted(map(int,my_list)) : # 排序
    print(i)

The result: full marks! It takes 31ms. Through symmetric processing, many operations are reduced.

Guess you like

Origin blog.csdn.net/weixin_43974265/article/details/104864741