I'm writing a ranking algorithm and I would like to add randomness factor .
I'm generating a list of 10 items where each item has a value from 1 to 10 :
l = [random.randint(1,10) for num in range(1, 11)]
I'm running this code around 400 times and storing the large list in a DB .
I would like to add probability to it, so 70% of the times it generate radom numbers between 1 and 5 for the first 5 items, and 5 to 10 for the last 5 items .
And 30% of the times it stays random without any probability (normal mode) .
How can I achieve this using python and it's random module ?
Edit : Some thinks that this might be a duplicate of this question, however it' not, because I'm not looking to choose items based on a probabiltiy, instead I would like to be distributed based on their weight .
The following will generate the wanted random list:
import random
def next_random_list():
# With 70% probability
if random.randint(1, 10) <= 7:
# Generate 5 random elements from 1 to 5
a = [random.randint(1, 5) for _ in range(5)]
# Generate 5 random elements from 5 to 10
b = [random.randint(5, 10) for _ in range(5)]
# Concatenate them
return a + b
else:
# Return just a random list of 10 numbers from 1 to 10
[random.randint(1, 10) for _ in range(10)]
and you can invoke it 400 times:
lists = [next_random_list() for i in range(400)]
Related
I've been working on a problem for a class that involves random number generation and returning a count for those divisible by 7 or 13. The function appears to work, or is at least returning the proper values along the steps. But, it returns a list for the count instead of a single value. What am I doing wrong? The requirements and my code so far are:
Develop and call a function that will:
Generate a random number n with a value between 1 and 1,000.
In the range of (n, n+200), iterate each number and count how many of them are divisible by 7 and how many of them are divisible by 13.
Print out the result
import random
def randDiv():
n = random.randint(1, 1000)
randList=[]
for x in range(n, n+200):
if (x%7==0) or (x%13==0):
randList.append(str(x))
total = len(randList)
print(total)
randDiv()
You are printing the total in each iteration. You should print it after for loop.
import random
def randDiv():
n = random.randint(1, 1000)
randList=[]
for x in range(n, n+200):
if (x%7==0) or (x%13==0):
randList.append(x)
print(len(randList))
randDiv()
I assume you mean that the function prints many values, as there is no return statement. Your print statement is nested, so each time (x%7==0) or (x%13==0) is True, it will increment the length of randList by 1 and print the length of total. Moving the final print statement outside the for loop should solve the problem.
In the for loop, you are checking if the current value is divided by 7 or 13 then add that value into the list. And every time, you are printing the length of the list. But if you want to print how many of them are divided by 7 and how many of them are divided by 13 separately, you have to take two different lists.
import random
def randDiv():
# n = random.randint(1, 1000)
n = 1
divBySeven=[]
divByThirteen=[]
divByThirteen
for x in range(n, n+200):
if (x%7==0):
divBySeven.append(x)
if x % 13 == 0:
divByThirteen.append(x)
print(len(divBySeven))
print(len(divByThirteen))
randDiv()
There have some numbers that are divided by both 7 and 13 such as 91. You have to consider that case also.
import itertools as itt
layer_thickness=[1,2,3,4,5]
permu= itt.permutations(layer_thickness,5)
permu_list=list(permu)
for i in permu_list:
if sum(i)==15:
print(i)
Here, I want permutations of the elements in the layer_thickness and those sum of the permutations should be to 5. But the number of elements in prmutation is not constrained by any limit unless it gives the desired sum.
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 , 2 2 2 2 2 2 2 1, etc are should be an element also.
what modifications should I do to achieve that?
You cant create all permutation as list for any total - it will simply hug too much memory:
Assuming [1,2,3,4,5] as numbers, 1 is your lowest element.
Assuming you want to reach a total = 15 - your "biggest" solution is (1,1,1,1,1,1,1,1,1,1,1,1,1,1,1).
To create all possible permutation of 5 numbers over 15 places you need to create 15**5 list entries: 15**5 = 2.562.890.625 possible number permutations
Storing each combination as 1 byte this would need 2.56 Terabyte of ram. Doubt you got that much.
The best you can do is to generate only numbers that work and quit out as soon as you reached your total. To do that for a fixed number set you can start with this question: Finding all possible combinations of numbers to reach a given sum
Using that and provide a "maximized" list of your numbers that can be added up to achieve your goal might lead to something:
def subset_sum(numbers, target, partial=[], partial_sum=0):
if partial_sum == target:
yield partial
if partial_sum >= target:
return
for i, n in enumerate(numbers):
remaining = numbers[i + 1:]
yield from subset_sum(remaining, target, partial + [n], partial_sum + n)
Credit: https://stackoverflow.com/a/4633515/7505395
def calc_nums_for_permutate(nums, total):
"""Creates a list of numbers from num - each single number is added as
many times as itself fits into total"""
return [n for n in nums for _ in range(total//n)]
if __name__ == "__main__":
nums = [1, 2, 3, 4, 5]
total = 15
print( *subset_sum( calc_nums_for_permutate(nums, total), total))
This will not work for all and any inputs - good luck with your runtime, this will still work reasonably well for a total = 10 - for a total = 15 it will take more time then I needed to format/copy paste and formulate this answer here.
I made a random number with this:
import random
number = random.randrange(0,100,2)
I want to iterate in it:
for i in number:
print(i)
or like that:
for number in range (50,100):
print number
I want to make a lists of random numbers, for example 50 random numbers between 0 and 100.
generate a sorted list of 50 different random numbers between 0 and 100 (not included) like this:
sorted(random.sample(range(0,100),50))
(pick 50 elements in the range object and sort them)
If you need/want repeats don't use sample just pick 50 numbers
sorted([random.randrange(0,100) for _ in range(50)])
or from python 3.6: sorted(random.choices(range(100),k=50))
For generating a list with n random numbers, you can use list comprehension. Such as,
lst = [random.randint(0,100) for _ in range(n)]
If you want to make a list of 50 random numbers between 1 and 100, you can do this:
import random
randlist = []
for i in range(50):
randlist += [random.randint(1, 100)]
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)
I am working with python 3.2 and I spent a lot of time trouble shooting this, and I still can't seem to wrap my brain around it.
number = random.randint ( x0 ,xn )
I'm generating a random number. It's purpose is to make my code come at me differently everytime.
For example I have 10 variables of text that I have written. I have solved the problem of not having these variables appear in the same order at each program run.
The issue I have is that they now appear randomly everytime. It picks one out of 10 everytime, instead the first time 10 and next 9. I can't seem to find out how to exclude the previous ones.
thelist = [0]
while i < x
if number in thelist:
>>>repeat<<<
else:
thelist.append (number)
if ( number == x0 ):
>>>something<<<
elif ( number == x1 ):
>>>something<<<
This is what I would imagine the code would look like, everytime you loop one more number gets appended to the list, so that everytime it picks a number already in the list it repeats the loop again until it then has used all the numbers that random.randint can pull.
Here's a shuffle function:
import random
max = 15
x = list(range(max+1))
for i in range(max, 0, -1):
n = random.randint(0, i)
x[n], x[i] = x[i], x[n]
This starts with a sorted list of numbers [0, 1, ... max].
Then, it chooses a number from index 0 to index max, and swaps it with index max.
Then, it chooses a number from index 0 to index max-1, and swaps it with index max-1.
And so on, for max-2, max-3, ... 1
As yosukesabai rightly notes, this has the same effect as calling random.sample(range(max+1), max+1). This picks max + 1 unique random values from range(max+1). In other words, it just shuffles the order around. Docs: http://docs.python.org/2/library/random.html#random.sample
If you wanted something more along the lines of your proposed algorithm, you could do:
import random
max = 15
x = range(max+1)
l = []
for _ in range(max+1):
n = random.randint(0,max)
while n in l:
n = random.randint(0,max)
l.append(n)
From what I understand of your description and sample code, you want thelist to end up with every integer between x0 and xn in a random order. If so, you can achieve that very simply with random.shuffle(), which shuffles a list in place:
import random
x0 = 5
xn = 15
full_range = list(range(x0, xn))
print(full_range)
random.shuffle(full_range)
print(full_range)