For this case the random value is generated at the beginning and only once, which will then be applied in all substitutions. These can be done based on a list of values to be replaced, and running through the two, with a double for
:
import random
posicao = [47, 62, 24, 18, 47, 62, 63, 78, 68, 87, 24, 18, 68, 87, 63, 78]
aleatorio = random.randrange(0,200)
for j in range(len(posicao)): #percorrer a lista original
if posicao[j] in [24,18]: #ver se o elemento se encontra nos que se quer trocar
posicao[j] = aleatorio #fazer a troca
Another solution is to use the method index
array to find the element. And although it is simpler to throw an exception if the element does not exist, in this case it would be if the element that wants to place the random does not exist in the array posicao
.
Controlling already these exceptions would be this way:
import random
posicao = [47, 62, 24, 18, 47, 62, 63, 78, 68, 87, 24, 18, 68, 87, 63, 78]
aleatorio = random.randrange(0,200)
for i in [24,18]: #valores a colocar o mesmo aleatório
try:
posicao[posicao.index(i)] = aleatorio
except:
pass
Edit
For a search and replacement by indexes can do:
import random
posicao = [47, 62, 24, 18, 47, 62, 63, 78, 68, 87, 24, 18, 68, 87, 63, 78]
aleatorio = random.randrange(0,200)
for i in [2, 3, 10, 11]: #indices a substituir aqui no for
posicao[i] = aleatorio
I believe the first way can be optimized. By doing the
for
ini
, you will go through the entire list twice, however, if you change theif
internal toif j in [24,18]
, thefor
ini
will not be necessary, going through the list only once. Another possible change would be to change therange(len(posicao))
forindex, value = enumerate(posicao)
.– Woss
@Andersoncarloswoss agree that at the syntactic level the
if j in
which I said is actually more optimized and I have already changed the answer to that. But unless the implementation of theif x in colecao
is not O(n) as I think it is, it remains a quadratic algorithm, O(n 2). Simply one of the linear searches is done at the expense of thisif
. Of course it would be possible to transform the algorithm into an O(nlogn) or even O(n) cost algorithm, but it would mean changing the structure of the original data to a tree or hash table respectively.– Isac
Thank you very, very much! For your help.
– Danilo
Sorry to ask again, but if I, instead of searching for the values [24, 18], search for their indexes, in case [2, 3, 10, 11]. How would be?
– Danilo
@Danilo already edited the answer for substitution by indices also
– Isac
@Isac Thank you very much!
– Danilo