A collection of exercises for Python beginners(Q23)
As a Python beginner, I’ve done a lot of practice. Most of these exercises are very interesting. In order for the other beginners to get to learn the basic usage of the language faster, I have compiled the results of my exercises for your reference. As I am a foreign student, this exercise is written in English. Most of the exercises come from 《C语言初学者趣味编程100例》(贾蓓/郭强/刘占敏). A small number of cases come from the Internet. If any case violates your rights, please tell me, and I will delete it as soon as possible.
Q23.Black hole number
Question:
A three-digit number with different digits will always get 495 after a finite number of “rearrangement and difference” operations. The final number, 495, is the number of three-digit black holes. The “rearrangement and difference” means subtract the minimum number of rearrangements from the the maximum number of rearrangements. Find the four-digit black hole number. (6174)
Python Code:
def sort(a):
list1=[]
list2=list1
b=a
while a>=1:
list1.append(a%10)
a=a//10
for i in range(len(list2)):
for j in range(i+1,len(list2)):
if list2[i]<list2[j]:
m=list2[i]
list2[i]=list2[j]
list2[j]=m
n=0
p=0
for k in range(len(list2)):
n=n+list2[k]*pow(10,len(list2)-1-k)
for l in range(len(list2)):
p=p+list2[l]*pow(10,l)
d=n-p
print(n,'-',p,'=',d)
return d
a=5671
b=0
while a!=b:
b=a
a=sort(a)
Running Results:
7651 - 1567 = 6084
8640 - 468 = 8172
8721 - 1278 = 7443
7443 - 3447 = 3996
9963 - 3699 = 6264
6642 - 2466 = 4176
7641 - 1467 = 6174
7641 - 1467 = 6174