python3 求4位磁力數

def split(n, numberlist):
    numberlist.clear()
    while(n > 0):
        mod = n % 10
        n = int( n / 10)
        numberlist.append(mod)
    return numberlist


def sort(largelist, len):
    for i in range(len):
        for j in range(len - i -1):
            if largelist[j] < largelist[j + 1]:
                tmp = largelist[j]
                largelist[j] = largelist[j + 1]
                largelist[j + 1] = tmp
    return largelist


 
def reverse(smalllist,k):
    for i in range(int(k / 2)):
        t = smalllist[i]
        smalllist[i] = smalllist[k - i -1]
        smalllist[k-i-1] = t
    return smalllist


def combine(list, k):
    temp = 0
    for i in range(k):
        temp1 = list[i] * pow(10, k - i -1)
        temp = temp + temp1
    return temp




n = eval(input("input a number: "))
len = len(str(n))
list = []


if len != 4:
    print("The valid input!")
    exit()


split(n, list)


if list[0] == list[1] == list[2] == list[3]:
    print("The valid input!")
    exit()
    


tarNum = 6174
    
while(n != tarNum):
    split(n, list)
    sort(list, len)
    max = combine(list, len)
    reverse(list, len)
    min = combine(list, len)
    n = max - min
    print("%d - %d = %d\n" % (max, min, n))
發佈了33 篇原創文章 · 獲贊 19 · 訪問量 10萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章