练习:构造一种算法来检查是否存在一半数组在阵列回文中(即从头开始阅读最后给出相同的结果)。在数组为奇数的情况下尺寸,中间元素被省略。
这是我到目前为止所做的,但是对于随机数却不起作用。
A = [1,2,2,1,5,4,5,5,4]
if A[0]+A[1] == A[2]+A[3] and A[5]+A[6] == A[7]+ A[8]:
print('works')
else:
print(' doesnt work ')
由于您添加了自己的尝试,所以我向您展示了一种使用Barmar评论中的想法的方法。
def split_list(a_list): # function which splits the array in two halfs
n = len(a_list)
if n % 2 != 0:
a_list.pop((n - 1) // 2)
half = len(a_list)//2
return a_list[:half], a_list[half:]
def palindrome(arr, n): # function which tests whether an array is a palindrome
flag = 0;
i = 0;
while (i <= n // 2 and n != 0):
if (arr[i] != arr[n - i - 1]):
flag = 1;
break;
i += 1;
if (flag == 1):
return "no palindrome"
else:
return "a palindrome"
arr = list(map(int, input().split()))
left_half, right_half = split_list(arr)
print("The left half array is " + str(palindrome(left_half, len(left_half))))
print("The right half array is " + str(palindrome(right_half, len(right_half))))