2017-09-15 50 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: 
相关问题