Program that creates two vectors with 10 random elements between 1 and 100

Asked

Viewed 1,573 times

-2

Make a program that creates two vectors with 10 random elements between 1 and 100. Generate a third vector of 20 elements, whose values should be composed of the interspersed elements of the two other vectors. Print the three vectors.

I wonder if the code I made is correct and if possible show me another way to do it thank you.

import random
lista1 = []
lista2 = []
lista3 = []

while len(lista1) < 10:
    numero = random.randint(1,100)
    if numero not in lista1:
        lista1.append(numero)
        lista3.append(numero)


while len(lista2)  < 10:
    numero = random.randint(1,100)
    if numero not in lista2:
        lista2.append(numero)
        lista3.append(numero)

lista1.sort()        
lista2.sort()
lista3.sort()

print(lista1)
print(lista2)
print(lista3)
  • 2

    Your show is doing something you didn’t expect?

  • 1

    I don’t really know if it’s the best way to do it.

1 answer

1


If you use the Sort method we will not be able to know if the elements are interspersed. An example: lista1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] and lista2 = [11, 12, 13, 14, 15, 16, 17, 18, 19, 20]. In this case the lista3 would be [1, 11, 2, 12, 3, 13, 4, 14, 5, 15, 6, 16, 7, 17, 8, 18, 9, 19, 10, 20].

I suggest dividing the logic into two parts: first to assemble the lists, without drawing lots and without worrying about having different elements. Then use the possible indexes, with range(10) to include the elements in the lista3 in a loop. First of all lista3.append(lista1[0]) lista3.append(lista2[0]) and so on.

Browser other questions tagged

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