I've seen multiple threads on printing lists of random numbers, but not ones with my specific requirements, and I can't seem to get it right.
I want to develop a code that will generate a list of random numbers on some interval, with the list being a random length alone some separate interval, also, duplicates need to be in this list. I also want to do it in 1 line.
I came up with a pretty good attempt using random.sample, but sample doesn't include duplicates, and it also won't let me make the range of numbers inside the list be larger than the list itself. (E.g. It can't generate a list 5 numbers long, but with numbers larger than 1 through 5.)
>> a = random.sample(range(10), random.randint(1,10,1))
>> print(a)
[6, 3, 4, 2, 5, 7, 8]
To get rid of the no duplicate problem, and numbers bigger than length problem, I attempted this, but I can't make the range random, or else I get a TypeError:
>> a = [random.randint(1,20) for x in range(1, 10)]
>> print(a)
[8, 7, 20, 20, 5, 18, 9, 3, 19]
Here is the version I attempted for random range:
>> a = [random.randint(1,20) for x in random.randrange(1,10)]
>> print(a)
Traceback (most recent call last):
File "<ipython-input-258-b3a6b0409007>", line 1, in <module>
a = [random.randint(1,20) for x in random.randrange(1,10)]
TypeError: 'int' object is not iterable
Not too sure why I can't create a random range on some interval, but I'm a beginner, so I'm sure I'm just missing something.
Aucun commentaire:
Enregistrer un commentaire