python: random sample with probabilities [duplicate] - python

This question already has answers here:
Weighted random sample in python
(6 answers)
Generate random numbers with a given (numerical) distribution
(13 answers)
Closed 7 years ago.
Suppose I want to create a sample of N elements chosen from [1,2,3] such that 1, 2 and 3 will be represented with weights 0.4,0.4 and 0.2 respectively. How would I do this.
I know how to do it in R without using loops:
mySample <- sample(c(1,2,3),size = 100,replace=T,prob = c(.4,.4,.2))

You can generate a random number in [0,1) then if it is in [0,.4) pick "1", else if it is in [.4,.8) pick "2" and else pick "3". the code is:
from random import random;
N = 10;
elements = [1,2,3];
weights = [.4, .4 , .2];
samples = range(N);
r = 0;
temp = 0;
for i in range(10):
r = random();
temp = 0;
for j in range(len(elements)):
temp += weights[j];
if(temp>r):
samples[i] = elements[j];
break;

Related

How to generate k percentages? [duplicate]

This question already has answers here:
Getting N random numbers whose sum is M
(9 answers)
Closed 8 months ago.
Given k a random integer between 2 and 7. How to generate a list of k positive numbers whose sum is equal to 1?
Examples of possible expected results:
k = 3 -> list = [0.23, 0.57, 0.2]
k = 3 -> list = [0.41, 0.44, 0.15]
K = 2 -> list = [0.95, 0.5]
You can generate k random numbers (for example in the range 0-1), then divide by their sum.
Example with numpy (for efficiency):
k = 3
import numpy as np
a = np.random.random(k)
out = (a/a.sum()).tolist()
pure python:
k = 3
import random
l = [random.random() for _ in range(k)]
s = sum(l)
out = [e/s for e in l]
example: [0.27830153962545046, 0.19826407925979248, 0.523434381114757]
I hope you are well.
you can use this code to do this:
import numpy as np
def softmax(x):
res = np.exp(x - np.max(x))
return res / res.sum()
size=5
list=np.random.random(size)
list=softmax(list)
Using a infinite loop which break once get all k numbers. Repeated numbers may occurs.
import random
#random.seed(3) # for testing purposes
k = 5
partition_of_unit = []
while True:
if len(partition_of_unit) == k-1:
break
n = random.random()
if sum(partition_of_unit) + n < 1:
partition_of_unit.append(n)
partition_of_unit.append(1-sum(partition_of_unit))
print(partition_of_unit)
#[0.6229016948897019, 0.029005228283614737, 0.11320596465314436, 0.013114189588902203, 0.22177292258463677]
print(sum(partition_of_unit))
#1.0

Given 3 non-negative integers, n, m, and a, what is the fastest way to find the smallest x such that (x*a) % n = m % n? [duplicate]

This question already has answers here:
Solving modular linear congruences for large numbers
(2 answers)
Closed 2 years ago.
Preferably, Id like a solution with time complexity O(1), O(log(n)), or O(sqrt(n)), since all the numbers are going to be pretty big.
Thanks in advance!
Note:
a < n
m < n
I'd use:
(m * pow(a,-1,n) ) % n
We want x, such that x = m/a, which is the same as m * 1/a. Python can do modular inverses automatically if you have the most recent version. :-)
Per the comment below, here's my modular Inverse function:
def findModularInverse(m,n) -> int:
"""Find m' such that m*m' === 1 (mod n)"""
if "HCF" not in globals(): HCF = __import__("math").gcd
assert HCF(m,n) == 1, "Not coprime."
s,sx,sy,t,tx,ty = m,1,0,n,0,1
while True:
q,r = s//t, s % t
u,ux,uy = r, sx-q*tx, sy-q*ty
#print("{} = {}x + {}y".format(u,ux,uy))
if r == 0: a,b = tx,ty; break
else: s,sx,sy,t,tx,ty = t,tx,ty,u,ux,uy; del q,r,u,ux,uy
return a%n
The poor thing has been deprecated and sent to the code retirement home.

Form all possible unique 3 digit number combinations from given elements in Python, [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
Consider a non-empty array inarr containing non-zero positive single digit integers, separated by ','
Print a string based on the following conditions:
Form all possible unique 3 digit number combinations with the elements of inarr
Identify the maximum number among the three-digit combinations formed
Print maximum number along with the total number of unique three-digit combinations formed, separating them with a ','.
Assumption: inarr contains at least 3 elements
Note: An element present at a particular index should not be considered more than once while forming a combination.
Input: Read inarr from standard input stream
Explanation: Sample Input 1,2,1,4 for the input inarr all possible unique 3 digit number combinations are: 121,411,124,214,114,142,141,211,421,112,241,412 The maximum number is 421 and total unique combinations are 12, therefore output will be 421,12
from itertools import permutations
elements = list(input("").split(',')) #makes a list of the input elements,
#splitting them at ','
p = permutations(elements, 3) #stores all possible permutations in p
x = list(set(p)) #set removes duplicates, stores a list in x
list = []
for i in x: #i iterates the elements in x, here a tuple
p = ''.join(i) #join concatenates the strings inside tuple
list.append(int(p))
list.sort()
print(str(list[-1])+','+str(len(list))) #prints the last element and length
JAVA :
import java.util.*;
class Sample
{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
String s = sc.nextLine();
String arr[] = s.split(",");
int freq[] = new int[10];
int count[] = new int[4];
for(String a : arr){
char c = a.charAt(0);
freq[c-'0']++;
}
for(int i = 0; i < 10; i++){
if(freq[i] == 0) continue;
if(freq[i]>3) freq[i] = 3;
switch(freq[i]){
case 3:
count[3]++;
case 2:
count[2]++;
case 1:
count[1]++;
}
}
//System.out.println(Arrays.toString(count));
String a = "";
for(int i = 9; i >=0; i--){
if(a.length()==3) break;
for(int j = 0; j < freq[i]; j++){
if(a.length()==3) break;
a = a + Integer.toString(i);
}
}
int ans = count[3];
ans += count[2] * (count[1]-1) * 3;
ans += count[1] * (count[1]-1) * (count[1]-2);
System.out.println(a+","+ans);
}
}

Circularly shifting (or rotating) the digits the digits of a number in Python [duplicate]

This question already has answers here:
Convert integer to string in Python
(14 answers)
Rotating strings in Python
(5 answers)
How do I parse a string to a float or int?
(32 answers)
Closed 7 months ago.
Suppose I have the following input:
1234
How can I get the following output?
3412
This is obtained by circularly shifting (or rotating) the digits of the input twice.
I have tried the following code:
number = 1234
bin(number >> 1)
but it is not producing the results I was expecting.
The >> operator does a binary bitshift.
It moves the binary representation of 1234 on place to the right, discarding the rightmost (least significant) bit.
Therefore you code does not result in 3412.
You probably want string rotation instead:
>>> def rotr(string, n):
... return string[n:] + string[:n]
...
>>> rotr("1234", 2)
'3412'
You can also convert it back to an integer afterwards
>>> int('3412')
3412
I would convert to string to be able to slice it.
number=1234
right_shift_no = 2
new_number = int(str(number)[right_shift_no:]+str(number)[:right_shift_no])
Here's the lazy man's version:
>>> from collections import deque
>>> number = 1234
>>> d = deque(str(number))
>>> d.rotate(2)
>>> result = int(''.join(d))
>>> result
3412
If you must stick with numbers (though I'd go with the string option first)
from math import log10, floor
s = 2 # digits to shift by
p = 10 ** s # that as a power of 10
n = 1234
rhs = n // p # right hand side of result (here 12)
rhs_n = floor(log10(rhs)) + 1 # number of digits in rhs
rhs + (n % p) * 10 ** rhs_n # add other digits, n % p, shifted by size of rhs
and all together in a function
from math import log10, floor
def rotate(n, s):
p = 10 ** s
rhs = n // p
return rhs + (n % p) * 10 ** (floor(log10(rhs)) + 1)

My own numerical system implementation [duplicate]

This question already has answers here:
Typecasting to 'int' in Python generating wrong result
(2 answers)
Closed 4 years ago.
I'm working with my own 91-numbers numerical system (unnonagesimal) in python 3.6 for RSA algorithm for my studies project. It works really fine but not with large numbers. Numbers I need it to work with are bigger than 1024 bits.
It doesn't work with some numbers, especially with those big ones.
The question is: Why doesn't it work?
Here's my code:
_unnonagesimal = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ.-:+=^/*?&<>()[]#%$#,;'`~|\"\\_"
def unnonagesimal_to_decimal(s):
return sum([_unnonagesimal.find(var) * len(_unnonagesimal) ** i
for i, var in enumerate(reversed(s))])
def decimal_to_unnonagesimal(n):
if n == 0:
return 0
else:
s = ""
while n != 0:
s += _unnonagesimal[n % len(_unnonagesimal)]
n = int(n / len(_unnonagesimal))
return s[::-1]
Where:
unnonagesimal_to_decimal(s) converts unnonagesimal string s into a decimal number.
and
decimal_to_unnonagesimal(n) converts decimal int n into an unnonagesimal number.
Alright, I just find out thanks to #user2357112
The problem was with int(blah / blah).
Corrected to int(blah // blah).
Now works fine.
This problem was becasue I switched to python 3 from python 2.
For anyone who doesn't know: in python 2, 5/2 = 2 but in python 3, 5/2 = 2.5 yet 5//2 = 2
I just thought dividing integers are the same in python 2 and 3.
Working code in python 3.6.5:
_unnonagesimal = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ.-:+=^/*?&<>()[]#%$#,;'`~|\"\\_"
def unnonagesimal_to_decimal(s):
return sum([_unnonagesimal.find(var) * len(_unnonagesimal) ** i for i, var in enumerate(reversed(s))])
def decimal_to_unnonagesimal(n):
if n == 0:
return 0
else:
s = ""
while n != 0:
s += _unnonagesimal[n % len(_unnonagesimal)]
n = int(n // len(_unnonagesimal))
return s[::-1]

Categories