Identify repeated indices and exchange only one of them

Asked

Viewed 55 times

0

I have the following vector:

a = [1, 2, 3, 4, 1, 3]

I need to go through this vector and identify which values are repeated.

After identifying them, I need only one of them to be exchanged for a random value between 1 and 11.

For example:

The exit vector would be something like this:

a = [1, 2, 3, 4, 10, 9]

That is, I identified that the indexes 0 and 2 are repeated. However, I change only the indexes 4 and 5 and keep the values of 0 and 2.

Could someone help me with this?

Grateful to those who can.

  • Only one or both?

  • only one of them.

  • It’s important to keep order?

  • 1

    Yes it is necessary to maintain!

  • @Jeffersonquesado if it is not possible to maintain order, no problem!

  • You can do it by keeping order, but making the set orderly allows for a few more lazy and quick approaches. See that answer, where I elaborate on identification of repeated elements in a set

Show 1 more comment

1 answer

2


A simple way is to go through all the values in a, check whether the current value belongs to the list b, which will be the output, and as long as it belongs, draw a new number between 1 and 11, until it is not present in the list and then add it. In Python, it would look like this:

from random import randint

a = [1, 2, 3, 4, 1, 3]
b = []

for value in a:
    while value in b:
        value = randint(1, 11)
    b.append(value)

print b

The result would be:

[1, 2, 3, 4, 8, 9]

That is, indices 4 and 5 were identified as duplicates and other values were drawn, in this Part 8 and 9 respectively.

See working on Ideone.

Even, this logic will work well with more than one repeated value. See:

from random import randint

a = [1, 2, 3, 4, 1, 1, 1, 1, 1]
b = []

for value in a:
    while value in b:
        value = randint(1, 11)
    b.append(value)

print b

Generating the result:

[1, 2, 3, 4, 7, 11, 8, 6, 10]

See working on Ideone.

However, if the list of values has more than 11 elements, there will come a time when the program will try to draw a value and never find a valid one, because all values between 1 and 11 belong to the list, getting stuck infinitely in the loop while - starting from the premise that the list of values will initially contain only values between 1 and 11. Thus, a check on the length of the list should be made to avoid such a problem:

from random import randint

a = [1, 2, 3, 4, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
b = []

if len(a) <= 11:
    for value in a:
        while value in b:
            value = randint(1, 11)
        b.append(value)

    print b
else:
    print "A lista 'a' deve conter no máximo 11 elementos."

See working on Ideone.

  • 1

    Thank you very much! It works perfectly for what I need.

Browser other questions tagged

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