rusttree
rusttree

Reputation: 19

Check if the element in sequence is larger than two previous elements

I want to check the input sequence is super increase, which is the elements in the sequence is larger than sum of previous elements.

for example, sequence (1, 3, 5, 7, 19) is not super increase because 1+3+5>7. Aequence [1, 3, 5, 11, 21] is super increase becuase 1<3, 1+3<5, 1+3+5<11, 1=3=5=11<21. Sequence [0, 0, 1, 2] is not super increase because 0=0. Sequence (-1, 0, 0, 1) is super increase and (1, 2, 0, 4) is not.

I try to wirte my code like this

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

but it says Sequence (-1, 0, 0, 1) is not super increase

How can I fix my code or I just need to change a method?

Upvotes: 0

Views: 246

Answers (2)

user2390182
user2390182

Reputation: 73470

You can do this with linear complexity using 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

That is basically a short-hand for:

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

Upvotes: 2

niaei
niaei

Reputation: 2419

You can use list slicing and a for loop for this.

Let's loop from 0 to length of the list. and sum all of values from first to ith element. If the sum is smaller then the ith element of the list the check for the ith element is True.

tf_list = []
for i in range(len(lst)):
    tf_list.append(sum(lst[:i]) < lst[i])

Now we can see if all values are True or not using all.

print(all(tf_list))

More pythonic way is to use list comprehensions:

all([sum(lst[:i]) < lst[i] for i in range(len(lst))])

Upvotes: 0

Related Questions