当第一个元素比下一个元素好时减去列表中的连续元素-Python
我正在制作一个程序,完成以下内容: 当输入一个列表当第一个元素比下一个元素好时减去列表中的连续元素-Python,python,list,performance,loops,subtraction,Python,List,Performance,Loops,Subtraction,我正在制作一个程序,完成以下内容: 当输入一个列表a时,如果结果是非负数,它将减去连续的元素(从开头开始)。 例如,如果 a=[3,2,1] 然后将连续的数字相减,因此a=[1,1],然后a=[0]。此外,在结果中,所有数字必须是升序的(例如,2,1不能在列表中)。另一个例子: a=[1, 10, 7, 3, 2] [1, 3, 3, 2] #10-7 (10 and 7 get replaced with 3) [1, 0, 2] #3-3 (precedence goes to t
a
时,如果结果是非负数,它将减去连续的元素(从开头开始)。
例如,如果
a=[3,2,1]
然后将连续的数字相减,因此a=[1,1]
,然后a=[0]
。此外,在结果中,所有数字必须是升序的(例如,2,1
不能在列表中)。另一个例子:
a=[1, 10, 7, 3, 2]
[1, 3, 3, 2] #10-7 (10 and 7 get replaced with 3)
[1, 0, 2] #3-3 (precedence goes to the left: 3-3 gets subtracted, not 3-2)
[1, 2] #1-0
这是我当前的代码(其中随机生成了一个):
随机导入
a=[random.randint(1,10)表示范围(20)内的e]
印刷品(a)
循环=1
尽管如此:
尝试:
#打印(循环,a)
子循环=0
而subloop以下是我对它的看法:
a = [1, 10, 7, 3, 2]
b = [3, 2, 1]
def index_helper(l):
for i, x in enumerate(l[:-1]):
if l[i] >= l[i+1]:
return i
def reduce(l):
i = index_helper(l)
while i is not None:
l[i:i + 2] = [l[i] - l[i + 1]]
i = index_helper(l)
return l
>>> reduce(a)
[1, 2]
>>> reduce(b)
[0]
另一种替代解决方案:
def my_func(a):
next_i = next((i for i in range(len(a)-1) if (a[i] - a[i+1]) >=0), None)
while next_i is not None:
a = a[:next_i] + [a[next_i] - a[next_i+1]] + a[next_i+2:]
next_i = next((i for i in range(len(a)-1) if (a[i] - a[i+1]) >=0), None)
return a
print(my_func(a=[1, 10, 7, 3, 2]))
#[1, 2]
print(my_func(a=[3, 2, 1]))
#[0]
import random
N = 10000
a_list = [[random.randint(1,10) for e in range(20)] for _ in range(N)]
all([reduce(l) == my_func(l) for l in a_list]) # verify answers are same
#True
%%timeit
[my_func(l) for l in a_list]
#10.7 ms ± 358 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
%%timeit
[reduce(l) for l in a_list]
#7.51 ms ± 416 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
但是,这比@bphi的解决方案略慢:
def my_func(a):
next_i = next((i for i in range(len(a)-1) if (a[i] - a[i+1]) >=0), None)
while next_i is not None:
a = a[:next_i] + [a[next_i] - a[next_i+1]] + a[next_i+2:]
next_i = next((i for i in range(len(a)-1) if (a[i] - a[i+1]) >=0), None)
return a
print(my_func(a=[1, 10, 7, 3, 2]))
#[1, 2]
print(my_func(a=[3, 2, 1]))
#[0]
import random
N = 10000
a_list = [[random.randint(1,10) for e in range(20)] for _ in range(N)]
all([reduce(l) == my_func(l) for l in a_list]) # verify answers are same
#True
%%timeit
[my_func(l) for l in a_list]
#10.7 ms ± 358 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
%%timeit
[reduce(l) for l in a_list]
#7.51 ms ± 416 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
第一个示例不应该以[0]
结尾吗<代码>[3,2,1]
->[1,1]
->[0]
是的。很抱歉,在您的示例中,为什么不执行10-7
和3-2
?每次迭代只有一次减法吗?即使你这样做了,结果不是仍然是[1,2]
。我不确定这是否有区别