Identify repeated indices and exchange only one of them

0

I have the following vector:

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

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

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

For example:

The output vector would look something like this:

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

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

Could anyone help me with this?

Thank you to those who can.

    
asked by anonymous 13.09.2017 / 03:07

1 answer

2

A simple way is to go through all values in% with%, check that the current value belongs to the a list, which will be the output, and as long as it belongs, draw a new number between 1 and 11 until it does not is 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, indexes 4 and 5 were identified as duplicates and other values were drawn in this case 8 and 9 respectively.

  

See working at Ideone .

In fact, 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 result:

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

See working at Ideone .

However, if the list of values has more than 11 elements, it will take an hour for the program to try to draw a value and never find a valid one, since all values between 1 and 11 belong to the list, getting trapped infinitely in the loop b - 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 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 at Ideone .

    
13.09.2017 / 03:34