PAT 1069 The Black Hole of Numbers python解法

1069 The Black Hole of Numbers (20 分)
For any 4-digit integer except the ones with all the digits being the same, if we sort the digits in non-increasing order first, and then in non-decreasing order, a new number can be obtained by taking the second number from the first one. Repeat in this manner we will soon end up at the number 6174 – the black hole of 4-digit numbers. This number is named Kaprekar Constant.

For example, start from 6767, we’ll get:

7766 - 6677 = 1089
9810 - 0189 = 9621
9621 - 1269 = 8352
8532 - 2358 = 6174
7641 - 1467 = 6174
… …
Given any 4-digit number, you are supposed to illustrate the way it gets into the black hole.

Input Specification:
Each input file contains one test case which gives a positive integer N in the range (0,10​4​​).

Output Specification:
If all the 4 digits of N are the same, print in one line the equation N - N = 0000. Else print each step of calculation in a line until 6174 comes out as the difference. All the numbers must be printed as 4-digit numbers.

Sample Input 1:
6767
Sample Output 1:
7766 - 6677 = 1089
9810 - 0189 = 9621
9621 - 1269 = 8352
8532 - 2358 = 6174
Sample Input 2:
2222
Sample Output 2:
2222 - 2222 = 0000

题意:给出一个4位数,将里面的数字按照降序排列减去按照增序排列,则可以得到一个新的数,重复这样做,最后会得到一个4位数:6174,称为数字黑洞。

解题思路:
1.把这个四位数转换成列表并复制给ninc(表示 non-increasing order)和ndec(表示non-decreasing order),将ninc按照非递增排序,ndec按照非递减排序。
2.因为ninc和ndec是列表形式,将它们转换为整形分别记做big和small。
3.计算big减small,存为dif。
4.按题目格式输出。
5.将上面的步骤写成一个函数cal,此时需要判断参数n是否是个4位数,因为dif可能不是一个4位数,比如2111-1112= 999。
6.函数的返回值为str(dif),因为开始的n也是一个字符串,保持类型一致。
7.先执行一遍n=cal(n),判断cal(n)是否等于‘0’,如果等于‘0’,说明n是一个每位都一样的4位数(如1111,1111-1111=0)。
8.如果不等于‘0’,进行循环,直到n==‘6174’。

n = input()
def cal(n):
    l = [i for i in n]
    if len(l) < 4:
        l.extend((4-len(l))*'0')
    ninc, ndec = l.copy(), l.copy()
    ninc.sort(reverse = True)
    ndec.sort()
    big = int(''.join(ninc))
    small =int( ''.join(ndec))
    dif = big - small
    print('%04d - %04d = %04d'%(big,small,dif))
    return str(dif)

n = cal(n)
if n != '0':
    while n != '6174':
        n = cal(n)

猜你喜欢

转载自blog.csdn.net/qq_36936510/article/details/86437392
今日推荐