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.
Only one or both?
– Jefferson Quesado
only one of them.
– Danilo
It’s important to keep order?
– Jefferson Quesado
Yes it is necessary to maintain!
– Danilo
@Jeffersonquesado if it is not possible to maintain order, no problem!
– Danilo
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
– Jefferson Quesado