Home > Enterprise >  How to check for a list item and the one after it in a list of integers
How to check for a list item and the one after it in a list of integers

Time:10-28

So I want to keep a subtotal but I want to subtract the number from the subtotal if it's smaller than the one to its right.

Example:

# [100, 100, 100, 10, 100, 5, 1, 1]

    for i in list:
        if i < i 1:
            num  = int(i)
        else:   
            num -= int(i)
    return num

I wanted this code to give me 397 but it adds the 10, doesn't subtract it

CodePudding user response:

For this use case, I think you want to iterate over the list indexes, not the list values. Then you can easily use the index to fetch the current value and the next value.

mylist = [100, 100, 100, 10, 100, 5, 1, 1]

for i in range(len(mylist)):
    curval = mylist[i]
    if i < len(mylist) - 1:
        nextval = mylist[i 1]
        if curval < nextval:
            num  = int(curval)
        else:   
            num -= int(curval)
    else:
        num  = int(curval)
return num

CodePudding user response:

you can achieve this using this.

l = [100, 100, 100, 10, 100, 5, 1, 1]
length = len(l)
num = 0
for index, value in enumerate(l):
    if value < l[index   1 if index < length - 1 else index]:
        num -= int(value)
    else:   
        num  = int(value)
print(num)

CodePudding user response:

Use zip to build tuples of the values. zip gets the original list and a copy with an offset of 1 as parameters. This idea might not be the best if the list is large.

data = [100, 100, 100, 10, 100, 5, 1, 1]

total = 0
for left_value, right_value in zip(data, data[1:]]):
    if left_value < right_value:
        total -= left_value
    else:
        total  = left_value
print(total)

The result is 396, but you wanted 397. So what's wrong? The last element in the list has no matching value because the list with the offset misses one element. But that's an easy fix. Just add the last element again.

for left_value, right_value in zip(data, data[1:]   [data[-1]]):

Alternative approach with a one-liner:

total = sum(-left if left < right else left for left, right in zip(data, data[1:]   [data[-1]]))

CodePudding user response:

Something simple could be this:

ls = [100, 100, 100, 10, 100, 5, 1, 1]

num = 0

for i, v in enumerate(ls):
    try:
        if ls[i] < ls[i 1]:
            num -= v
    except:
        pass

The manage exception is to avoid the an IndexError

Output:

-10

CodePudding user response:

The easy way to iterate over consecutive pairs of items in a list is to zip the list with a slice of itself. Using sum and a simple ternary expression you can write this in one line:

>>> nums = [100, 100, 100, 10, 100, 5, 1, 1]  # don't call a list "list"
>>> sum(a if a >= b else -a for a, b in zip(nums, nums[1:]))   nums[-1]
397

Note that nums[-1] is a special case since it has no consecutive number b, and here we're choosing to add it to the sum unconditionally.

  • Related