简体   繁体   中英

How to compare 4 consecutive elements in a list?

I am new to coding so I apologize in advance if what I am asking is simple or doesn't make much sense but I will try to elaborate as much as I can. First of all this is not for any work or project I am simply studying to learn a bit of coding for my satisfaction. I've been trying to find some real life problems to apply into coding (pseudo code mostly but python language would also be kind of understandable to me).

I wanted to be able to have a list of x elements and compare 4 of them sequentially.

For example, myList = [a, b, c, d, e, f, g, h, i, j, k, l]

First I want to compare a,b,c and d. If b>a, c>b, d>c and d> all of 3 previous ones ( d>a, d>b, d>c ) I want to do something otherwise go to next comparison.

Then I wanted to compare b,c,d and e. Similarly if c>b, d>c, e>d and e> all of 3 previous ones ( e>b, e>c, e>d ) I want to do something otherwise go to next comparison.

What if my list contains infinite elements? myList = [:] Where do I start? Do I have to have a starting point?

I am guessing I have to use a for loop to iterate through the list but I honestly can't figure out how to iterate through the first 4 elements and then continue from the second element in 4 element batches.

Since I am currently studying the Arrays and lists maybe there is some functionality I am missing? Or I simply my brain can grasp it.

I tried looking at other posts in stackoverflow but honestly I can't figure it out from other people's answers. I would appreciate any help or guidance.

Thanks in advance.

You can use the built-in all() function for this problem:

myList = [5, 4, 3, 6, 3, 5, 6, 2, 3, 10, 11, 3]

def do_somthing():
    #your code here
    pass

for i in range(len(myList)-4):
     new_list = myList[i:i+4] #here, using list slicing to jump ahead four elements.
     if all(new_list[-1] > b for b in new_list[:-1]) and all(new_list[:-1][c] > new_list[:-1][c+1] for c in range(len(new_list)-2)):
         do_something()
L = [...]
# get all the valid indices of the elements in the list, except for the last 4. These are the indices at which the 4-element windows start
for i in range(len(L)-4):
    window = L[i:i+4]  # the 4 elements you want to compare
    print("I am considering the elements starting at index", i, ". They are:", window)
    a,b,c,d = window
    if d>a>b>c<d and d>b:
        print("The checks pass!")

Now, there is a simpler way to do this:

for a,b,c,d in (L[i:i+4] for i in range(len(L)-4):
    if d>a>b>c<d and d>b:
        print("The checks pass!")

Since you can index a list, how about start from index 0, compare the 0th, (0+1)th, (0+2)th, and (0+3)th elements. Then, by the next round, increase your index to 1, and compare the 1st, (1+1)th, (1+2)th, and (1+3)th elements, and so on. For the nth round, you compare the n, n+1, n+2, and (n+3)th elements, until you reach the 4th element before the end. This is how you generally do stuff like 'testing m elements each time from a sequence of length n', and you can easily expand this pattern to matrices or 3d arrays. The code you see in other answers are basically all doing this, and certain features in Python make this job very easy.

Now, 'what if the list contains infinite elements'? Well, then you'll need a generator, which is a bit advanced at this stage I assume, but the concept is very simple: you let a function read that infinite stream of elements in a (might be infinite) loop, set a cursor on one of them, return ( yield ) the element under the cursor as well as the 3 elements following it each time, and increase the cursor by one before the next loop starts:

def unsc_infinity(somelist):
    cur = 0
    while True:
        yield somelist[c:c+4]
        cur = cur + 1

infinity_reader = unsc_infinity(endless_stream)
next(infinity_reader)
# gives the 0, 1, 2, 3 th elements in endless_stream
next(infinity_reader)
# gives the 1, 2, 3, 4 th elements in endless_stream
next(infinity_reader)
# ...

And you can loop over that generator too:

for a, b, c, d in unsc_infinity(endless_stream):
    if d>a>b>c<d and d>b:
        do_something()

Hope that helps a bit for you to build a mental model about how this kind of problems are done.

to consume just one item at a time from an iterator and operate on 4 lagged elements try a circle buffer:

# make a generator as example of 'infinte list'
import string
agen = (e for e in string.ascii_lowercase)

# initialize len 4 circle buffer
cb = [next(agen) for _ in range(4)]  # assumes there are at least 4 items
ptr = 0  # initialize circle buffer pointer

while True:
    a,b,c,d = (cb[(i+ptr)%4] for i in range(4))  # get current 4 saved items

    # some fuction here
    print(a,b,c,d)  

    # get next item from generator, catch StopIteration on empty
    try:
        cb[ptr] = next(agen)
    except StopIteration:
        break
    ptr = (ptr + 1)%4  # update circle buffer pointer
a b c d
b c d e
c d e f
d e f g
e f g h
f g h i
g h i j
h i j k
i j k l
j k l m
k l m n
l m n o
m n o p
n o p q
o p q r
p q r s
q r s t
r s t u
s t u v
t u v w
u v w x
v w x y
w x y z

'some function' could include a stopping condition too:

 # random.choice() as example of 'infinte iterator'
import string
import random
random.choice(string.ascii_lowercase)

# initialize len 4 circle buffer
cb = [random.choice(string.ascii_lowercase) for _ in range(4)]  # assumes there are at least 4 items
ptr = 0  # initialize circile buffer pointer


while True:
    a,b,c,d = (cb[(i+ptr)%4] for i in range(4))  # get current 4 saved items

    # some fuction here
    print(a,b,c,d)
    if a<b<c<d:  # stopping condition
        print("found ordered string: ", a,b,c,d)   
        break

    # get next item from generator, catch StopIteration on empty
    try:
        cb[ptr] = random.choice(string.ascii_lowercase)
    except StopIteration:
        break
    ptr = (ptr + 1)%4  # update circle buffer pointer
o s w q
s w q k
w q k j
q k j r
k j r q
j r q r
r q r u
q r u v
found ordered string:  q r u v

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM