I am trying to create a random list of 1 million numbers ranging between 1-100. I have found how to create a single random number but not to create a list of them. In addition, I would prefer to use the numpy uniform function but the solution doesn't have to use this.
For a big array, you'd better use numpy
import numpy as np
X = np.random.randint(1, 101, size=10**6)
Try this simpler one :
from random import randint
my_list = [randint(1, 100) for i in range(1000000)]
The function
np.random.rand(Dim1,Dim2)
will create an array for the given dimensions with values selected from the uniform distribution [0,1]. You can modify this to randomArray = 1 + 99 * np.random.rand(Dim1,Dim2) to have the array with numbers ranging between 1-100.
from random import *
mylist = []
for i in range(0, 100):
f = randint(0, 100)
mylist.insert(i, f)
This code will give 100 random elements to your empty list.
use this as simple as that...don't make your program more complex in code and in efficiency too..
from random import randint
l=[randint(1,100) for i in range(0,1000000)]
Related
What is the best way to implement a random event in Python?
For example:
The variable a is set to 1 with a probability of 0.8 and otherwise to 2.
I've done this until now as following:
import random
a = 0 #Initialize a to 0
prob = random.random() #ask Python for a random float between 0 and 1
if prob < 0.8:
a = 1
else:
a = 2
Is there another way for such cases?
You can use random.choices:
import random
a = random.choices([1, 2], weights=[0.8, 0.2])[0]
You can use numpy random with values and their probabilities
from numpy.random import choice
a = [0,2]
output = choice(a, 1, p=[0.8,0.2])
print(output)
Syntax: numpy.random.choice(list,k, p=None)
List: It is the original list from you have select random numbers.
k: It is the size of the returning list. i.e, the number of elements you want to select.
p: It is the probability of each element.
You could use random.choices to make it a little more pythonic.
a = random.choices([1,2], weights = [4, 1])[0]
Continuous form distribution
Continuous form distribution is explained on Wikipedia, and grants you to have the same probability of extracting each value in the interval [0, 1). That's exactly what you want to have: the probability of 80% of getting a=1 and 20% of getting a=2.
Numpy python implementation
Using numpy.random.random_sample() you can achieve this, from docs:
Results are from the “continuous uniform” distribution over the stated
interval.
import numpy as np
rand = np.random.random_sample() # sample output: 0.5320258785026352
I personally prefer to write your code like this:
import random
prob = random.random()
a = 1 if prob < 0.8 else 2
I am trying to create 8 random pairs from a list of from given 10 images.
import random
imageList = ['1.jpg','2.jpg','3.jpg','4.jpg','5.jpg','6.jpg','7.jpg','8.jpg','9.jpg','10.jpg']
for i in range(len(imageList)):
imagepair = range(len(imageList) - 1)
You can simply shuffle the list, then take the first 4 items from it, and repeat once more:
for _ in range(2):
random.shuffle(imageList)
i=0
while(i<8):
print(imageList[i], imageList[i+1])
i+=2
You can use random.shuffle and create a generator to get samples of image groups as many times as needed.
def image_generator(l):
while True:
random.shuffle(l)
yield l[:2]
for i in range(8):
print(next(image_generator(imageList)))
['6.jpg', '2.jpg']
['10.jpg', '5.jpg']
['8.jpg', '6.jpg']
['6.jpg', '1.jpg']
['5.jpg', '3.jpg']
['8.jpg', '6.jpg']
['6.jpg', '2.jpg']
['8.jpg', '2.jpg']
Another way is you can use itertools.product to get permutations of n (or 2) for images, filtering out cases where both images are the same. And then you can use random.sample to get 8 samples.
import random
import itertools
def image_generator(iterable, groups, samplesize):
grouped = (i for i in itertools.product(imageList,repeat=2) if i[0]!=i[1])
return random.sample(list(grouped), samplesize)
image_generator(imageList, 2, 8)
[('8.jpg', '7.jpg'),
('7.jpg', '10.jpg'),
('7.jpg', '2.jpg'),
('6.jpg', '7.jpg'),
('5.jpg', '3.jpg'),
('2.jpg', '1.jpg'),
('10.jpg', '5.jpg'),
('9.jpg', '10.jpg')]
use random function to get 2 integers as index values and pair the corresponding image.
I want to create a random number using n numbers which are between i and j. For instance, for n=10 and i=1 and j=5, such an output is expected: 2414243211. I did it in R using this code:
paste(floor(runif(10,1,5)),collapse="") #runif create 10 random number between 1 and 5 and floor make them as integer and finally paste makes them as a sequence of numbers instead of array.
I want to do the same in Python. I found random.uniform but it generates 1 number and I don't want to use loops.
import random
import math
math.floor(random.uniform(1,5)) #just generate 1 number between 1 and 5
update:
i and j are integers between 0 and 9, while n could be any integer.
i and j decide which number can be used in the string while n indicates the length of the numeric string.
If I understand your question (not sure I do), and you have Python 3.6, you can use random.choices:
>>> from random import choices
>>> int(''.join(map(str, choices(range(1, 5), k=10))))
2121233233
The random.choices() function does what you want:
>>> from random import choices
>>> n, i, j = 10, 1, 5
>>> population = list(map(str, range(i, j+1)))
>>> ''.join(choices(population, k=n))
'5143113531'
If you consider list-comprehensions being loops (which they actually in many ways are) there you will not be satisfied with this but I will try my luck:
from random import randint
res = ''.join([str(randint(1, 5)) for _ in range(10)])
print(res) #-> 4353344154
Notes:
The result is a string! If you want an integer, cast to int.
randint works incluselively; the start (1) and end (5) might be produced and returned. If you do not want that, modify them (start = 2 and end = 4)
Is there a reason you are using random.uniform (and subsequently math.floor()) and not simply randint?
x = ''.join([str(math.floor(random.uniform(1,5))) for i in range(10)])
I generated random numbers, and easily calculated their means. My question is, however, how can I see the numbers I generated? I'd like to save these numbers to a vector. How can I do this?
This is my code:
import random
print ("#n\tmean")
for n in (1,10,100):
sum = 0
mean = 0
for i in range(n):
sum += random.random()
mean = sum / n
print ("%d\t%g\t" % (n, mean))
Thank you in advance!
Use list comprehensions,
import random
n = 100
l = [random.random() for _ in range(n)]
mean = sum(l)/100
use a list to save all the results:
results = []
for i in range(n):
sum += random.random()
mean = sum / n
results.append(mean)
then get the output array by:
np.hstack(results)
I think you need something like this, if you want to avoid numpy.
import random
print ("#n\tmean")
meansList = []
for n in (1,10,100):
sum = 0
mean = 0
for i in range(n):
sum += random.random()
mean = sum / n
meansList.append(mean)
print meansList
Try python's in-built data structure list which I think is closes to a vector and would work for you.
vector = list()
//in the for loop
r = random.random()
vector.append(r)
Also note that lists can append lists since you have two for loops. For example you can do something like
outer_vector.append(inner_vector)
Use the numpy package
import numpy as np
my_numbers = np.random.uniform(0, 1, 100)
print np.mean(my_numbers)
You can generate the mean of random for 1, 10, 100 in one line using list comprehension:
import random
result = [(n,sum(random.random() for _ in range(n))/n) for n in (1,10,100)]
print(result)
one possible output:
[(1, 0.1269484085194036), (10, 0.6572300932440089), (100, 0.4796109974064649)]
random.random() for _ in range(n) is the generator comprehension that feeds sum, divide by n to get the mean, wrapped in an outer loop and creating tuples with value/mean
I am new to programming and I got stuck with random number generation. I can simply generate random numbers using random function "randint" but could not generate set of random numbers. For instance i want to get 10 random numbers.
from random import randint
x = randint(1, 100)
y = randint(1, 100)
isFailedTest = (5<=x<=15) and (10<=y<=11)
selected_test = [x,y]
while (isFailedTest == False):
I can generate 1 random number at one time but not 10 at one time. Here 1 number mean 2 dimensional number example (x,y) = (10,20) I want to get 10 random numbers (x,y) after my while condition. How do I achieve that? I am very new to programming so could not figure out what could be done. All help/ suggestion/ recommendation is highly appreciated.Thank you.
Simple solution
array = [(randint(1, 100), randint(1, 100)) for i in range(10)]
Better solution
The following solution is more flexible and reusable.
from functools import partial
from random import randint
def randints(count, *randint_args):
ri = partial(randint, *randint_args)
return [(ri(), ri()) for _ in range(count)]
print(randints(10, 1, 100))
Requirement - "Here 1 number mean 2 dimensional number example (x,y) = (10,20) I want to get 10 random numbers (x,y)"
>>> from random import randint as r
>>> array = [ (r(1,100), r(1,100)) for i in xrange(10)]
from random import randint
r = []
N = 10
for x in range(N):
a = randint(5,15) # rand number between 5 and 15
b = randint(10,11) # rand number between 10 and 11
r.append((a,b))
# r <-- contains N tuples with random numbers
Why don't you just do:
from random import randint
randoms = []
for i in range(10):
randoms.append((randint(1,100),randint(1,100)))
Then randoms will be an array of 10 integers, randomly generated between 1 and 100 (inclusive).
To be quite clear: what is going on here is that you make an empty list called randoms. Then the for loop executes ten times, each time appending a new tuple of two random integers to the list randoms.
NumPy should do the job
np.random.randint(low=1, high=100, size=10)