9. The perfect number

9. PerfectNumber. Py:

#! /usr/bin/python
# Env: python3
# Rewrite by afei_0and1

9. A positive integer is called perfect if it is equal to the sum of all its positive factors. Now, given a number N, determine if it's perfect. 28 = 1+2+4+7+14 28 = 1+2+4+7+14 28 = 1+2+4+7+14 Here's the trick: if you find one factor, you find another, except for 1 and itself, which come in pairs. Perfect numbers are also called perfect numbers or perfect numbers. The first perfect number in nature was 6, and the number 6 often has a special meaning. According to historical records, the first person to study the perfect number was Pythagoras in 6 BC. He had already found two perfect numbers in existence: 6 and 28. Pythagoras had said that 6 was the symbol of perfect marriage and health and beauty because it was complete and the sum of its factors was equal to itself. In addition, some Biblical believers believe that 6 and 28 are the basic numbers God used to create the world in six days, and 28 is the number of days it took the moon to make a full circle around the Earth. In ancient Chinese culture, numbers 6 and 28 were endowed with more meanings, such as the six livestock, six grain and six constant related to 6, and the twenty-eight stars related to 28. There is something magical about the perfect number, and many coincidences have been associated with it throughout history. So far, the exact number of perfect numbers is still a mystery, and the process of finding the perfect number is not easy. By February 6, 2013, a total of 48 perfect numbers had been discovered. Similarly, perfect numbers are rare, with the 13th perfect number already 314 bits long. After that, perfect numbers are even more terrifying, with an estimate that the 39th perfect number printed in 4-point print is the thickness of a dictionary. Since the discovery of the perfect number, many mathematicians and mathematical enthusiasts have been tirelessly looking for the perfect number in nature, which is a difficult process, until the development of computer science, the search efficiency of the perfect number has been improved. Amazingly, all the perfect numbers found so far have been even, and no odd perfect numbers have been found. ' ' '

import math

def perfectNumber(N) :
    if N <= 0:
        return False
    res = 0
    
    for i in range(1.int(math.sqrt(N)) + 1) :if N % i == 0:
            res += i
            # Remove the case where the two factors are the same
            ifi * i ! = N: res += N / i# because it comes in pairs, we have to multiply by 2
    if res == N * 2:
        return True
    return False
print(perfectNumber(28))

Output result: True

Table lookup: There are only five perfect numbers within 33550336:6, 28, 496, 8128 and 33550336.

def checkPerfectNumber(N) :
    return True if N in [6.28.496.8128.33550336] else False
print(checkPerfectNumber(8128))

Output result: True
Copy the code

Number 10. Happy

10. HappyNumber. Py:

#! /usr/bin/python
# Env: python3
# Rewrite by afei_0and1

Take a positive integer and replace it each time with the sum of its squares at each position. Then repeat the process until the number becomes 1. It may go on indefinitely but never becomes 1. For example, 19 is a happy number, which can be proved as follows: 1^2 + 9^2 = 82 8^2 + 2^2 = 64 6^2 + 8^2 = 100 1^2 + 0^2 + 0^2 = 1 ' ' '

def happyNumber(N) :
    # Define a temporary list of all disassembled numbers
    tmp = [N]
    whileN ! =1:
        # Convert the input number to a list
        l = list((str(N)))
        res = 0
        for i in l:
            res += int(i) * int(i)
        # If res is TMP, terminate the loop, it is not a happy number
        if res in tmp:
            return False
        tmp.append(res)
        N = res
    return True
print(happyNumber(91))

Output result: True
Copy the code

11. A suitable number

11. SuitableNumber. Py:

#! /usr/bin/python
# Env: python3
# Rewrite by afei_0and1

Define order as an integer in which each digit is 1 greater than the preceding digit. For example, 123, 234, 345, and 456 are sequential numbers. Now, given a range, e.g. [1000, 10000], try to programmatically find all sequential degrees in the range and return them as a constituent list from smallest to largest.

def suitableNumber(low, high) :
    l = []
    Select * from '321' to '1'
    for num in range(1.10) :# fetch the first two digits from the left, as shown above: 21
        for j in range(num+1.10):
            num = num * 10 + j
            if num <= high and num >= low:
                l.append(num)
    # Order from left to right, smallest to largest
    l.sort()
    return l
print(suitableNumber(1000.10000))


Output result: [1234, 2345, 3456, 4567, 5678, 6789]
Copy the code

12. A few progress

12. ProgressNumber. Py:

#! /usr/bin/python
# Env: python3
# Rewrite by afei_0and1

12. A progressive number is an extension of order. An integer is progressive if the absolute difference between each of its digits and its neighbors is 1. For example, 321 is a progressive number, 421 is not. Now, given a range, try to programmatically find all the progressions in its range and return them as a list from smallest to largest. ' ' '

def progressNumber(low, high) :
    # save all progress numbers
    l = [0]
    Store all filtered progress numbers in res
    res = []
    Define a pointer
    p = 0
    # add the special progress number 0
    if low <= 0:
        res.append(0)
    Filter out one-digit progress numbers
    while l[-1] < 9:
        l.append(l[-1] + 1)
        if l[-1] >= low and l[-1] <= high:
            res.append([-1])
    while l[-1] < high:
        current = l[p]
        if current == 0:
            p += 1
            continue
        # The number of two or more steps can only be greater than the boundary 0 if the first to last is the boundary 0
        if str(current)[-1] = ="0":
            nex = current * 10 + int(str(current)[-1]) + 1
            l.append(nex)
            if nex >= low and nex <= high:
                res.append(nex)
        If the last digit is the boundary 9, it can only be smaller than it
        elif str(current)[-1] = ="9":
            nex = current * 10 + int(str(current)[-1]) - 1
            l.append(nex)
            if nex >= low and nex <= high:
                res.append(nex)
        # If neither of them is met, the boundary is between 2 and 8
        else:
            nexLeft = current * 10 + int(str(current)[-1]) - 1
            nexRight = current * 10 + int(str(current)[-1]) + 1
            l.append(nexLeft)
            l.append(nexRight)
            if nexLeft >= low and nexLeft <= high:
                res.append(nexLeft)
            if nexRight >= low and nexRight <= high:
                res.append(nexRight)
            p += 1
    return res
print(progressNumber(10.15))

Output result: [10, 12]

Copy the code

13. Centrally symmetric numbers

13. Center_symmeter_num. Py:

#! /usr/bin/python
# Env: python3
# Rewrite by afei_0and1

Definition of centrosymmetric number: a number that looks the same when rotated 180 degrees. For example, if the number 69 is rotated 180 degrees and still 69, 69 is a centrally symmetric number. Now, entering an arbitrary string number requires programming to determine whether it is a centrosymmetric number. ' ' '

def func(num) :
    # set up the mapping between numbers 0 and 9
    dic = {"0":"0"."1":"1"."2":"1"."3":"1"."4":"1"."5":"1"."6":"9"."Seven":"1"."8":"8"."9":"6"}
    l = []
    for i in num:
        if dic[i] == "1":
            return False
        Insert into the first element position, automatically reverse
        l.insert(0, dic[i])
    return  num == "".join(l)

print(func("96"))

Output result: True
Copy the code

14. Look for centrosymmetric numbers

14. Search_center_symmeter_Num. Py:

#! /usr/bin/python
# Env: python3
# Rewrite by afei_0and1

We learned in the previous article that a centrosymmetric number is a number that looks the same after being rotated 180 degrees. Now, we need to programmatically find all centrosymmetric numbers of length N. For example, if N is 2, all the centrosymmetric numbers are "11", "69", "88" and "96". (1) If the number of centrosymmetric digits is odd, the middle number must be one of the three digits: 0, 1, and 8. Because these are the only three numbers that are still equal to themselves when rotated 180 degrees. And if you start at the center and spread out, the numbers on the two sides must come in pairs. Five pairs of numbers: 00, 11, 88, 69 and 96. (2) If it is an even number, the numbers taken from left to right and from right to left must be paired. ' ' '

S = ['0'.'1'.'8']  #N=1 centrosymmetric number
D = ["00"."11"."88"."69"."96"]  # Double bit expansion on both sides
d = ["11"."88"."69"."96"]  Centrosymmetric number when #N=2

def func(l, N) :
    res = []
    # Two-bit judgment
    if N > 1:
        for i in D:
            for item in l:
                tmp = list(item)
                tmp.insert(len(tmp) // 2, i)
                res.append("".join(tmp))
        if res == []:
            res = d
        return func(res, N - 2)
    # odd digit judgment
    if N == 1:
        for i in S:
            for item in l:
                tmp = list(item)
                tmp.insert(len(tmp) // 2, i)
                res.append("".join(tmp))
        if res == []:
            res = S
        return func(res, N - 1)
    return  l

print(func([], 3))

"' the Output result: [' 101 ', '808', '609', '906', '111', '818', '619', '916', '181', '888', '689', '986'] ' ' '
Copy the code

More Leetcode: blog.csdn.net/qq_41490561…