2017-09-15 53 views
0

我在python中編寫了下面的代碼來檢查第i個術語和第n-1個術語的相等性。我得到一個錯誤首先結束for循環(在)。請幫助Python代碼來檢查第i個和第i-1個術語的相等性

arr=[] 
n=int(input("Enter the number of terms you want in the array")) 


for i in range(0,n): 
     a=int(input("Enter your number here")) 
     arr.append(a) 

for i in range(0,len(arr)): 
    if arr[i]==arr[len(arr)-i-1]: 
     print("The "+i+"th element and the "+len(arr)-i-1+"th element are equal") 

回答

1

您的這個代碼片段的第二個for循環的邏輯是不正確。您應該在arr上致電len()而不是a。所以你的第二個循環應該看起來像:

for i in range(0, len(arr)): 
    if arr[i] == arr[len(arr) - i - 1]: 
     print("The " + str(i) + "th element and the " + str(len(a) - i - 1) + "th element are equal") 

希望這有助於!

編輯:爲了適應重複的結果,你就必須解決這個for循環經過迭代的次數。所以for循環則是這樣的:

# Halve the number of iterations so it doesn't repeat itself 
for i in range(0, len(arr) // 2): 
    ... 

編輯2:找出正確的結局對於一個特定的數字,嘗試類似以下內容:

if not (10 < i < 14): 
    if i % 10 == 1: 
     print("st") 
    # elif, etc... 
    else: 
     print("th") 
+0

非常感謝您的回答。我仍然面臨錯誤。我正在得到多餘的答案。如第0和第4項相等,第4和第0項相等。如何消除這個問題? –

+0

@joeylang根據新規格編輯我的回覆。 – Jerrybibo

+0

我相信你的編輯存在缺陷。如果最後兩個元素相等,將範圍減半,您將錯過它。 – Flynsee

3
for i in range(0,len(a)): 
    if arr[i]==arr[len(a)-i-1]: 
     print("The "+i+"th element and the "+len(a)-i-1+"th element are equal") 

應該是:

for i in range(0,len(arr)): 
    if arr[i]==arr[len(arr)-i-1]: 
     print("The "+i+"th element and the "+len(arr)-i-1+"th element are equal") 

你也不能轉換的int STR含蓄:

print("The "+i+"th element and the "+len(arr)-i-1+"th element are equal") 

應該

print("The {}th element and the {}th element are equal".format(i,len(arr)-i-1)) 

終於擺脫了冗餘的,取代:

if arr[i]==arr[len(arr)-i-1]: 

有:

if arr[i]==arr[len(arr)-i-1] and len(arr)-i-1>i: 
相關問題