我想檢查輸入序列是否超增,也就是序列中的元素大于前面元素的總和。
例如,序列 (1, 3, 5, 7, 19) 不是超增,因為 1 3 5>7。等式 [1, 3, 5, 11, 21] 是超增的,因為 1<3, 1 3<5, 1 3 5<11, 1=3=5=11<21。序列 [0, 0, 1, 2] 不是超增,因為 0=0。序列 (-1, 0, 0, 1) 是超級增加,而 (1, 2, 0, 4) 不是。
我試著像這樣寫我的代碼
def super_increasing(seq):
if any(seq[i 1] <= seq[i] for i in range(0,len(seq)-1)):
return False
else:
if all(seq[i 2]>seq[i 1] seq[i] for i in range(0,len(seq)-2)):
return True
else:
return False
但它說 Sequence (-1, 0, 0, 1) 不是超級增加
如何修復我的代碼或者我只需要更改一個方法?
uj5u.com熱心網友回復:
您可以使用itertools.accumulate以下線性復雜度來做到這一點:
from itertools import accumulate
def super_increasing(seq):
return all(t < c for c, t in zip(seq[1:], accumulate(seq)))
super_increasing([1, 3, 5, 7, 19])
# False
super_increasing([1, 3, 5, 11, 21])
# True
這基本上是以下內容的簡寫:
def super_increasing(seq):
t, *rest = seq # t: running total
for c in rest: # c: current element
if c <= t:
return False
t = c
return True
uj5u.com熱心網友回復:
您可以為此使用串列切片和 for 回圈。
讓我們從 0 回圈到串列的長度。并對從第一個i元素到第 th 個元素的所有值求和。如果總和小于i串列的第 th 個元素,則對第 th 個元素的檢查i是True。
tf_list = []
for i in range(len(lst)):
tf_list.append(sum(lst[:i]) < lst[i])
現在我們可以查看是否所有值都True使用all.
print(all(tf_list))
更 Pythonic 的方法是使用串列推導式:
all([sum(lst[:i]) < lst[i] for i in range(len(lst))])
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/347557.html
標籤:Python
