python3 实现数学黑洞6174

6174猜想:一个任意的四位正整数(全相同的除外,如1111)。将数字重新组合成一个最大的数和最小的数相减,重复这个过程,最多七步,必得6174。

6174百度百科

还有一个数是495,和6174一个道理,一个任意的三位正整数,然后排列最大减去最小,重复下去一直到495
用python3实现:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
# -*- coding: utf-8 -*-
from functools import reduce
x = str(input("请输入四位数或者三位数的数字: "))
times = 1
while True:
if len(x) > 4:
print("不能超过4位数")
break
max_math = sorted(x,reverse=True)
min_math = sorted(x)
max_math_switch_str = int(reduce(lambda x,y:x+y,max_math))
min_math_switch_str = int(reduce(lambda x,y:x+y,min_math))
s = max_math_switch_str-min_math_switch_str
print("now",times,max_math_switch_str,"-",min_math_switch_str,"=",s)
if s == 6174:
break
if s == 495:
break
x = str(s)
times += 1

下面是运行结果:

mathematics_black_hole.png