繁体   English   中英

列表中相邻元素之间的差异越来越大

[英]Strictly increasing difference between adjacent elements in a list

编写一个函数expanding(l),该函数将一个整数l的列表作为输入,如果每对相邻元素之间的绝对差严格增加,则返回True。

我尝试执行此代码,但这对于某些列表未返回正确的值。

def expanding(l):
 for i in range(0,len(l)-3):
  if (abs(l[i+2]-l[i+1])>abs(l[i+1]-l[i])):
   Answer=True
  else:
   Answer=False
 return Answer

expanding([1,3,7,2,-3])应该为False,但输出为True

使用临时变量存储差异,并在达到非递增差异时退出。

def expanding(l):

    dif = abs(l[1] - l[0])

    for i in range(1, len(l)-1):
        temp = abs(l[i+1] - l[i])

        # Non-increasing difference, return
        if temp < dif:
            return False
        else:
            dif = temp

    # All differences are increasing
    return True

Numpy是您的朋友:

import numpy as np

x=np.array([1,3,7,2,-3])
(np.diff(abs(x[1:] - x[:-1])) > 0).all()  # returns False


如果您喜欢一个函数,我会这样:

def expanding(l):
    # convert list to  np.array if a list was passed
    if isinstance(l, list):
        l = np.array(l)

    return (np.diff(abs(l[1:] - l[:-1])) > 0).all()

使用迭代器的另一种解决方案:

from itertools import tee, islice, starmap
from operator import lt, sub

def pairwise(x):
    a, b = tee(x, 2)
    return zip(a, islice(b, 1, None))

a = [1,3,7,2,-3]

pairs = pairwise(a) # this will be (a[0], a[1]), (a[1], a[2]), ...

# The next will produce the result abs(a[1]-a[0]), abs(a[2]-a[1]), ...
differences = map(abs, starmap(sub, pairs))

# This will be abs(a[2]-a[1])>abs(a[1]-a[0]), abs(a[3]-a[2])>abs(a[2]-a[1]), ...
cmp = starmap(lt, pairwise(differences))

# Differences strictly increases if all items in cmp are evaluated to True...
result = all(cmp)
print(result)

此类输入的输出为False

我建议您在迭代器中写入条件,然后将其传递给any迭代器,以确保在第一次出现非扩展差异时,迭代停止并返回False

外观如下:

def expanding(l):
    return not any((abs(l[i-1]-l[i])>=abs(l[i]-l[i+1]) for i in range(1,len(l)-1)))

您的逻辑有点错误。 一旦您知道一项商品出现故障,您应该为整个清单回答False。

def expanding(l):
 for i in range(0,len(l)-3):
  if (abs(l[i+2]-l[i+1])<=abs(l[i+1]-l[i])):
   return False 
 return True
def expanding(l):
 for i in range(0,len(l)-2):
  if (abs(l[i+2]-l[i+1])>abs(l[i+1]-l[i])):
   Answer=True
  else:
   Answer=False
   return Answer
 return Answer

expanding([1,3,7,2,-3]) 

一旦您知道一项有问题,就应该对整个列表回答False,而不用等待,这样其他对就不会改变答案。

还要注意从range(0,len(l)-3)range(0,len(l)-2) 最初的实现缺少最后一对列表元素。

Debkanta Mondal编写的代码

Python3

def expanding(l):
dif=[]
for x,y in zip(l,l[1:]):
    diff=abs(y-x)
    dif.append(diff)
return all(i<j for i,j in zip(dif,dif[1:]))

打印(展开([1,3,7,2,-3]))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM