【问题标题】:Given an array of N elements. The task is to check if the elements in the array are first strictly increasing then strictly decreasing给定一个包含 N 个元素的数组。任务是检查数组中的元素是否首先严格增加然后严格减少
【发布时间】:2021-08-18 16:32:08
【问题描述】:
  • 示例: 输入:arr[] = [-3, 9, 11, 20, 17, 5, 1] 输出:是的

输入:arr[] = [5, 6, 7, 8, 9, 10, 1, 2, 11] 输出:否

我尝试了方法,但它的抛出错误是列表索引超出范围。 我还需要在每次迭代中增加“i”吗?

def checkType(arr,n):
  for i in range(len(arr)):
    #print(i)
    if (arr[i]<=arr[i+1]): #and (arr[n-1]<=arr[n-2]):
      print('YES')
    else:
      print('NO')
if __name__ == "__main__" :
  arr=[-3, 9, 11, 20, 17, 5, 1]
  n=len(arr)
  checkType(arr,n)

IndexError: 列表索引超出范围

【问题讨论】:

    标签: python


    【解决方案1】:

    你可以这样做:-

    arr = [-3, 9, 11, 20, 17, 5, 1]
    
    if sorted(arr) == arr or sorted(arr, reverse=True) == arr:
      print('The array is ordered - either ascending or descending')
    else:
      print('The array is not ordered')
    

    【讨论】:

      【解决方案2】:

      试试下面的代码:

      arr = [-3, 9, 11, 20, 17, 5, 1]
      lst = [x - y for x, y in zip(arr, arr[1:])]
      y = 1
      value = 'YES'
      for i in lst:
          if ((i < 0) != y) and (y == 1):
              y = 0
          elif ((i < 0) != y) and (y == 0):
              value = 'NO'
              break
      print(value)
      

      输出:

      YES
      

      【讨论】:

      • 代码已经算好了,能不能把我写的代码优化一下?
      猜你喜欢
      • 2021-10-10
      • 1970-01-01
      • 1970-01-01
      • 2021-01-30
      • 2023-03-08
      • 2022-01-02
      • 1970-01-01
      相关资源
      最近更新 更多