[英]How to check if the sum of all the previous elements in the array are greater than the next element in the array?
[英]Check whether list element is greater than previous elements
我在 Python 中有一個這樣的列表:
mylist = [13, 8, 7, 5, 6, 3, 9]
我想檢查列表中的每個元素,它是否大於或等於前面的元素。 如果這是真的,我想加 1 並檢查它是否等於先前的元素。 如果發生這種情況,請添加數字,直到不再正確為止。
我希望你能理解,我想存檔什么。 mylist 的輸出將是
outputlist = [13, 8, 7, 5, 9, 3, 10]
所以mylist
的6
大於5
所以它加上1
,現在它是7
,它已經存在。 所以它添加了另一個1
(value = 8
) 和另一個1
(value = 9
)。
初始列表中的“9”等於新計算的 9,因此加 1。
注意:順序很重要,所以排序mylist
不是一個選項。
不是很漂亮,但我沒有找到更短的方法來做到這一點。 不過似乎有效。
def magic(lst):
lst = lst[:] # create copy
seen = set() # prior values as set
for i in range(len(lst)):
if any(lst[i] >= x for x in lst[:i]): # greter/equal than any prior
lst[i] += 1 # first increment
while lst[i] in seen:
lst[i] += 1 # increment more
seen.add(lst[i]) # add to prior set
return lst
例子:
>>> magic([9, 9, 9, 9])
[9, 10, 11, 12]
>>> magic([13, 8, 7, 5, 6, 3, 9])
[13, 8, 7, 5, 9, 3, 10]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.