Compare two to two elements of a vector

Asked

Viewed 36 times

-1

Good afternoon! I am studying python3 (I am very beginner), and I would like, given a vector, to compare the elements of this vector 2 to 2 to see if they are equal. for example: [2,3,4,4,5] 2 compares with 3, and we have that 2!=3 3 compares with 4, and we have that 3!=4 4 compares with 4, and we have that 4==4 4 compares with 5, and we have that 4!=5

What I thought was something like

for x in vetor2:
   if vetor2[x]==vetor2[x+1]:

Meanwhile, out of range... thank you!

  • Just iterate to the length -1.

  • Hi! And how could I do that?

2 answers

-1

One way to implement it would be:

vetor = [2,3,4,4,5]
for x in range(len(vetor)-1):
    if vetor[x]==vetor[x+1]:
        print('sim')
    else: 
        print('não')

For this code I used the functions len and range that are part Built-in Functions python.

Explaining the code

The function range will generate a sequence of immutable numbers up to a value.

When used with an integer type parameter, this function will generate numbers up to the value passed as parameter (in this case it will be the len(vetor)-1).

Already the function len returns the number of items of an object (object here can be: string, array, list, tuple or Dictionary, Python types)

-2

Could do so:

for i in range(1, len(vetor2)):
    if vetor2[i]==vetor2[i-1]:
        print(vetor2[i])

That is, starting from 1 (the first position is zero) and comparing with the previous (i-1)

Or so, limiting to size at least 1 (len(vetor2)-1) and compared with the next without letting go of the limit and give the error of your question.

for x in range(len(vetor2)-1):
    if vetor2[x]==vetor2[x+1]:
        print(vetor2[x])
  • Thank you very much!!!

  • @Romulorebello if the answer helped vote for it or mark it as right, because we do not help and there are people who like to give negative votes without "apparent reason", which discourages to help

Browser other questions tagged

You are not signed in. Login or sign up in order to post.