我已經編寫了代碼,用於確定哪些自然數小於或等於1 000 000是完美的數位不變量(它們可以寫成它們每個數字的總和)以等於數字的力量;參見https://en.wikipedia.org/wiki/Perfect_digit-to-digit_invariant)並且以這種形式表示它們。用於數位不變量的Python代碼
def f(n):
y = str(n)
l = len(y)
list = []
for i in range(0,l):
list.append(int(y[i]))
list2 = []
for i in list:
list2.append(i**i)
return sum(list2)
N = 10**6
n = np.linspace(1,N,N,dtype=int)
list = []
for i in n:
if i == f(i):
list.append(i)
list = np.array(list)
list2 = []
for i in list:
list2.append(str(i))
for i in list2:
for j in range(0,len(i)-1):
print(i[j],'^',i[j],'+')
print(i[-1],'^',i[-1],'=',int(i))
print('----------')
運行此代碼給出的輸出爲:
1^1 = 1
----------
3^3 +
4^4 +
3^3 +
5^5 = 3435
----------
該代碼提供了正確的答案,但我希望表達式3^3 + 4^4 + 3^3 + 5^5 = 3435出現在一行上。有沒有辦法做到這一點?
'打印(I [j]時, '^',1 [j]時, '+',端= '')' –