2017-06-06 70 views
3

我已經編寫了代碼,用於確定哪些自然數小於或等於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出現在一行上。有沒有辦法做到這一點?

+4

'打印(I [j]時, '^',1 [j]時, '+',端= '')' –

回答

2

print()默認情況下,也會打印換行符。爲了抑制這種行爲,並繼續在同一行打印,添加end=''參數,像這樣:

for i in list2: 
    for j in range(0, len(i)-1): 
     print(i[j],'^',i[j],'+', end='') 
    print(i[-1],'^',i[-1],'=',int(i)) 
    print('----------') 

或者,更pythonically你可以通過join()代替內環荷蘭國際集團串成品的配件和格式化輸出,如下所示:

for i in list2: 
    print(' + '.join(['{0:}^{0:}'.format(x) for x in i]) + ' = {}'.format(i)) 
    print('----------') 
0

嘗試end=" "選項打印

for j in range(0,len(i)-1): 
    print(i[j],'^',i[j],'+', end=" ")