Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I generate a random list in Python with duplicates numbers

Tags:

python

list

So I just started programming in Python a few days ago. And now, im trying to make a program that generates a random list, and then, choose the duplicates elements. The problem is, I dont have duplicate numbers in my list.

This is my code:

import random

def generar_listas (numeros, rango):
    lista = [random.sample(range(numeros), rango)]
    print("\n", lista, sep="")
    return
def texto_1 ():
    texto = "Debes de establecer unos parámetros para generar dos listas aleatorias"
    print(texto)
    return

texto_1()
generar_listas(int(input("\nNumero maximo: ")), int(input("Longitud: ")))

And for example, I choose 20 and 20 for random.sample, it generates me a list from 0 to 20 but in random position. I want a list with random numbers and duplicated.

like image 557
iMasck Avatar asked Dec 24 '22 01:12

iMasck


2 Answers

What you want is fairly simple. You want to generate a random list of numbers that contain some duplicates. The way to do that is easy if you use something like numpy.

  • Generate a list (range) of 0 to 10.
  • Sample randomly (with replacement) from that list.

Like this:

import numpy as np
print np.random.choice(10, 10, replace=True)

Result:

[5 4 8 7 0 8 7 3 0 0]

If you want the list to be ordered just use the builtin function "sorted(list)"

sorted([5 4 8 7 0 8 7 3 0 0])
[0 0 0 3 4 5 7 7 8 8]

If you don't want to use numpy you can use the following:

print [random.choice(range(10)) for i in range(10)]
[7, 3, 7, 4, 8, 0, 4, 0, 3, 7]
like image 141
Mohammed Elmahgiubi Avatar answered Dec 26 '22 14:12

Mohammed Elmahgiubi


random.randrange is what you want.

>>> [random.randrange(10) for i in range(5)]
[3, 2, 2, 5, 7]
like image 27
citaret Avatar answered Dec 26 '22 14:12

citaret