Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I generate a number of random numbers that are all odd

import random

myfile = open('numbers.txt', 'w')
file_size = random.randint(4,7)

for count in range(file_size):
    numbers = random.randint(5,19)
    myfile.write(str(numbers) + '\n')

myfile.close()

This what I have so far, but I need the numbers to be all odds and the right amount of odds that the "file_size" is telling the code. Each integer must be random, between 5 and 19 inclusive.

like image 463
Mike Avatar asked Feb 08 '23 13:02

Mike


2 Answers

You can use random.randrange which accepts optional step parameter:

>>> import random
>>> random.randrange(5, 19+1, 2)
9
like image 108
falsetru Avatar answered Feb 12 '23 11:02

falsetru


To generate an odd number between 1 and 10 use random.randrange(start,end,step)

odd_rand_num = random.randrange(1,10,2)
odd_rand_num = 7

To generate a list of random odd numbers please use this:

odd_rand_list = [random.randrange(1,10,2) for p in range(0,10)]
odd_rand_list = [3, 9, 7, 9, 1, 1, 9, 7, 3, 9]
like image 40
Pallawi.ds Avatar answered Feb 12 '23 12:02

Pallawi.ds